C#TCPIP通信,Socket通信例⼦1、服务端建⽴监听,等待客户端连接
class Program
{
static void Main(string[] args)
socket通信报文格式{
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);
Console.WriteLine("1.服务端建⽴监听");
listener.Start();
Console.WriteLine("等待客户端连接");
TcpClient tcpClient = listener.AcceptTcpClient();
Console.WriteLine("2.1客户端已经连接");
Console.WriteLine("2.2获取到客户端传过来报⽂流");
NetworkStream stream = tcpClient.GetStream();
Console.WriteLine("3.初始化⼀个字节数组");
byte[] data = new byte[1024];
Console.WriteLine("4.从流中读取内容到字节数组");
int length = stream.Read(data, 0, 1024);
Console.WriteLine("5.将字节数组中的内容解析为字符串");
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("6.打印");
Console.WriteLine(message);
Console.WriteLine("7.关闭流");
stream.Close();
Console.WriteLine("8.停⽌监听者");
listener.Stop();
Console.WriteLine("9.程序结束");
Console.ReadKey();
}
}
2.从主机连接得到客户端
class Program
{
static void Main(string[] args)
{
Console.WriteLine("0.声明⼀个客户端");
TcpClient tcpClient = new TcpClient("127.0.0.1", 8000);
Console.WriteLine("1.从客户端得到⼀个流");
NetworkStream stream = tcpClient.GetStream();
Console.WriteLine("2.请输⼊要发送的内容");
string message = Console.ReadLine();
Console.WriteLine("3.将输⼊的字符串解析为字节数组");
byte[] data = Encoding.UTF8.GetBytes(message);
Console.WriteLine("4.将字节内容写⼊流");
stream.Write(data, 0, data.Length);
Console.WriteLine("5.关闭流");
stream.Close();
Console.WriteLine("7.关闭客户端");
tcpClient.Close();
Console.WriteLine("8.程序结束");
Console.ReadKey();
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论