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 = 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, real【原URL http://www.yidunidc.com/usa.html复制请保留原URL】en); 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<string>(s => { this.textBox_Message.Text = string.Format("{0}\r\n{1}", s, textBox_Message.Text); } ), txt); //同步方法 //textBox_Message.Invoke(new Action<string>(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方法的整型参数表示的是:排队等待连接的最大数量,注意这个数量不包含已经连接的数量
以上为个人经验,希望能给大家一个参考,也希望大家多多支持海外IDC网。如有错误或未考虑完全的地方,望不吝赐教。
【文章出处:国内服务器】