Instantly detect client disconnection from server socket

后端 未结 14 1673
北恋
北恋 2020-11-22 09:27

How can I detect that a client has disconnected from my server?

I have the following code in my AcceptCallBack method

static Socket hand         


        
14条回答
  •  借酒劲吻你
    2020-11-22 09:47

    This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.

    //open or receive a server socket - TODO your code here
    socket = new Socket(....);
    
    //enable the keep alive so we can detect closure
    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
    
    //create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
    void MonitorSocketsForClosureWorker() {
        DateTime nextCheckTime = DateTime.Now.AddSeconds(5);
    
        while (!exitSystem) {
            if (nextCheckTime < DateTime.Now) {
                try {
                    if (socket!=null) {
                        if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
                            //socket not connected, close it if it's still running
                            socket.Close();
                            socket = null;    
                        } else {
                            //socket still connected
                        }    
                   }
               } catch {
                   socket.Close();
                } finally {
                    nextCheckTime = DateTime.Now.AddSeconds(5);
                }
            }
            Thread.Sleep(1000);
        }
    }
    

提交回复
热议问题