这篇文章给大家分享的是有关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, 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<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方法的整型参数表示的是:排队等待连接的最大数量,注意这个数量不包含已经连接的数量
感谢各位的阅读!关于“C#怎么实现Socket通信”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!