TCPIP服務端檢測客戶端斷開方法
阿新 • • 發佈:2019-02-01
當接收到的資料長度=0的時候此時客戶端就請求斷開連線了。就這麼簡單public class TCPIPServer { #region 成員 private static TCPIPServer tcpIPServer; private static Socket socket; #endregion #region 屬性 #endregion #region 方法 /// <summary> /// 建立伺服器 /// </summary> /// <param name="port"></param> /// <returns></returns> public static TCPIPServer CreateServer(int port) { if (tcpIPServer == null && socket == null) { return tcpIPServer = new TCPIPServer(port); } return tcpIPServer; } private TCPIPServer(int port) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, port); socket.Bind(ipEndPoint); socket.Listen(10); BeginAccept(socket); } /// <summary> /// TCPIP訊息事件 /// </summary> public event EventHandler<ClientInfoEvent> TcpMsgEvent; /// <summary> /// TCPIP登陸事件(不支援獲取TCPIP資料) /// </summary> public event EventHandler<ClientInfoEvent> TcpClientInfoEvent; private Dictionary<string, Socket> ConnectionList = new Dictionary<string, Socket>(); private void BeginAccept(Socket objsocket) { objsocket.BeginAccept(callback=> { var client= objsocket.EndAccept(callback); var ip = client.RemoteEndPoint.ToString(); if (!ConnectionList.ContainsKey(ip)) { ConnectionList.Add(ip,client); TcpClientInfoEvent?.Invoke(tcpIPServer,new ClientInfoEvent(ConnectionList)); } BeginReceive(client,0); BeginAccept(objsocket); },null); } private void BeginReceive(Socket objsocket,int num) { byte[] buffer = new byte[4096]; objsocket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,callback=> { var length= objsocket.EndReceive(callback); if (length>0) { var bytes = new byte[length]; Array.Copy(buffer,bytes,length); TcpMsgEvent?.Invoke(tcpIPServer,new ClientInfoEvent(new UdpReceiveResult(bytes,objsocket.RemoteEndPoint as IPEndPoint), ConnectionList)); num = 0; BeginReceive(objsocket, num); } else if(length==0)//就是我length=0就是斷開了 { ConnectionList.Remove(objsocket.RemoteEndPoint.ToString()); objsocket.Dispose(); } },null); } public void Send(byte[] buffer, EndPoint endpoint) { ConnectionList[endpoint.ToString()].BeginSend(buffer,0,buffer.Length,SocketFlags.None,callback=> { ConnectionList[endpoint.ToString()].EndSend(callback); },null); } #endregion }