C# socket服务端判断 客户端已经断开连接的一个小办法

具体原理就是:
If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.
中文翻译:如果远程主机关闭 Socket 与连接 Shutdown 方法,并且所有可用数据已被接收, Receive 方法将立即完成并返回零字节。

详见MSDN:跳转到MSDN

下面是一段示例代码,其核心就是这个Socket.Receive方法(好吧,在本例中使用的是”myClientSocket.Receive”)

private void ReceiveMessage(object clientSocket)
        {
            byte[] result = new byte[1024];
            Socket myClientSocket = (Socket)clientSocket;
            if (myClientSocket == null)
            {
                return;
            }
            string clientId = myClientSocket.RemoteEndPoint.ToString();
            if (string.IsNullOrWhiteSpace(clientId) || !myClientSocket.Connected)
            {
                return;
            }
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    if (!myClientSocket.Connected)
                    {
                        RemoveClient(clientId);
                        break;
                    }

                    myClientSocket.ReceiveTimeout = 100000; //设置超时时间,如果超过此时间没收到客户端的心跳数据,则端口客户端连接

                    //receiveNumber 显示接收的字节数,当它等于0时,说明已经接收完所有可用数据,并且断开了socket的连接
                    int receiveNumber = myClientSocket.Receive(result);
                    string msg = Encoding.Default.GetString(result, 0, receiveNumber);
                    if (receiveNumber == 0)
                    {
                        //看这个receiveNumber, 当它等于0的时候,说明已经断开了客户端的连接

                        //这里代码不全,就权当看个意思~
                        RemoveClient(clientId);
                        break;
                    }
                    else if (!string.IsNullOrWhiteSpace(msg)
                        && msg.Length == 1
                        && msg[0] == (char)5 //查询字符串
                        )
                    {
                        //说实话我不太知道这个else if作用是啥,就先放这以后研究吧~
                        myClientSocket.Send(Encoding.Default.GetBytes(new char[] { (char)4 }));

                    }
                    else
                    {
                        myClientSocket.Send(Encoding.Default.GetBytes(string.Format("收到客户端{0}的消息:{1}", clientId, msg)));

                    }
                }
                catch (Exception ex)
                {

                }
            }
        }

你可能感兴趣的:(C#)