C#|C# Socket通信的实现(同时监听多客户端)
看代码~
//创建socket对象//第一个参数:设置网络寻址的协议、第二参数设置数据传输的方式、第三个参数设置通信协议Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.绑定IP端口string str = "127.0.0.1"; int ports = 55555; IPAddress ip = IPAddress.Parse(str); IPEndPoint ipENdpoint = new IPEndPoint(ip, ports); serverSocket.Bind(ipENdpoint); //3.开启监听serverSocket.Listen(10); label5_Timer.Text = "开始监听···"; //4.开始接受客户端的链接ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartAcceptClient), serverSocket); }public void StartAcceptClient(object state){var serverSocket = (Socket)state; this.AppendTextLog("服务器开始接受客户端的链接"); while (true){try{Socket prosock = serverSocket.Accept(); //将远程链接的客户端的IP地址和socket存入集合中dicSocket.Add(prosock.RemoteEndPoint.ToString(), prosock); string ipPort = prosock.RemoteEndPoint.ToString(); MedicineDevice ns = new MedicineDevice(); SQLMachine j = new SQLMachine(); j.MedicineDeviceStatus(ipPort, "在线"); //链接对象的信息string stinfo = prosock.RemoteEndPoint.ToString(); this.AppendTextLog(string.Format("客户端{0}链接上了", stinfo)); ClientProSocketList.Add(prosock); //服务器接收客户端的消息ThreadPool.QueueUserWorkItem(new WaitCallback(this.ReceiveData), prosock); }catch (Exception e){return; //throw; } }
public void ReceiveData(object obj){var prosock = (Socket)obj; byte[] data = https://www.it610.com/article/new byte[1024 * 1024]; //方法返回代表实际接受的数据的长度while (true){int realen = 0; try{realen = prosock.Receive(data, 0, data.Length, SocketFlags.None); }catch (Exception e){//异常退出AppendTextLog(string.Format("设备 {0} 异常退出", prosock.RemoteEndPoint.ToString())); StopCOnnecte(prosock); return; }if (realen <= 0){//对方正常退出 AppendTextLog(string.Format("设备 {0} 正常退出:", prosock.RemoteEndPoint.ToString())); }prosock.Shutdown(SocketShutdown.Both); prosock.Close(); ClientProSocketList.Remove(prosock); return; }//接受到的数据string fromClientMsg = Encoding.Default.GetString(data, 0, realen); AppendTextLog(string.Format("接收到 {0} 的消息是:{1}", prosock.RemoteEndPoint.ToString(), fromClientMsg)); }}private void StopCOnnecte(Socket prosock){try{if (prosock.Connected){prosock.Shutdown(SocketShutdown.Both); prosock.Close(100); }}catch (Exception ex){ }} public void AppendTextLog(string txt){if (textBox_Message.InvokeRequired){textBox_Message.BeginInvoke(new Action(s =>{this.textBox_Message.Text = string.Format("{0}\r\n{1}", s, textBox_Message.Text); }), txt); //同步方法//textBox_Message.Invoke(new Action(s =>//{//this.textBox_Message.Text = string.Format("{0}\r\n{1}", s, textBox_Message.Text); //}//), txt); }else{this.textBox_Message.Text = string.Format("{0}\r\n{1}", txt, textBox_Message.Text); }}//在粘贴代码时可能有漏'{'或'}'
补充:C# Socket的Listen监听方法
看代码~
_serverSocket.Listen(10); public void Listen(int backlog);
Listen方法的整型参数表示的是:排队等待连接的最大数量,注意这个数量不包含已经连接的数量
【C#|C# Socket通信的实现(同时监听多客户端)】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- Docker应用:容器间通信与Mariadb数据库主从复制