TcpListener 、TcpClient_01
客户端:
System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(); tcpClient.Connect(hostname: "127.0.0.1", port: 12345); var stream = tcpClient.GetStream(); while (true) { byte[] message = Encoding.UTF8.GetBytes($"发送:{DateTime.Now.ToString()}"); //写入数据流 stream.Write(message, 0, message.Length); Console.WriteLine($"{Encoding.UTF8.GetString(message)}"); Thread.Sleep(1000);
服务端:
{ TcpListener listener = new TcpListener(IPAddress.Loopback, 12345); listener.Start(); byte[] buffer = new byte[20]; var clientStream = listener.AcceptTcpClient().GetStream(); Task.Factory.StartNew(() => { while (true) { // 读取数据流 clientStream.Read(buffer, 0, buffer.Length); var message = Encoding.UTF8.GetString(buffer); Console.WriteLine($"{message}"); // Console.WriteLine($"{ex.Message}{ex.StackTrace}"); } }); Console.ReadLine(); }