上位机与通信组件(三)
1、基于C#的以太网通信对象
using System.Net.Sockets;
2、socket服务启动监听
1 # region Socket TCP 服务端 2 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 创建Socket对象 3 socket.Bind(new IPEndPoint(IPAddress.Any, 9000)); // 绑定ip地址和端口 IPAddress.Any 127.0.0.1 4 socket.Listen(); // 启动服务监听 5 #endregion
3、socket服务接收消息
1 List<Socket> clientList = new List<Socket>(); 2 3 Task.Run(() => 4 { 5 while (true) 6 { 7 Socket client = socket.Accept(); // 同步 8 clientList.Add(client); 9 Task.Run(() => 10 { 11 while (true) 12 { 13 // 接收到一个消息后 转发出去 14 byte[] buffer= new byte[1024]; 15 client.Receive(buffer); // 卡线程 16 string msg = Encoding.UTF8.GetString(buffer); 17 msg = msg.Replace("\0", ""); 18 Console.WriteLine($"从客户端接收到:{msg}"); 19 msg += "- 服务端发送"; 20 client.Send(Encoding.UTF8.GetBytes(msg)); 21 } 22 }); 23 } 24 });