C# TCP/IP通信,Socket通信例子
1、服务端建立监听,等待客户端连接
class Program { static void Main(string[] args) { 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(); } }