Instantly detect client disconnection from server socket

后端 未结 14 1448
北恋
北恋 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:51

    Someone mentioned keepAlive capability of TCP Socket. Here it is nicely described:

    http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html

    I'm using it this way: after the socket is connected, I'm calling this function, which sets keepAlive on. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received.

        void SetKeepAlive(bool on, uint keepAliveTime, uint keepAliveInterval)
        {
            int size = Marshal.SizeOf(new uint());
    
            var inOptionValues = new byte[size * 3];
    
            BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
            BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, size);
            BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, size * 2);
    
            socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
        }
    

    I'm also using asynchronous reading:

    socket.BeginReceive(packet.dataBuffer, 0, 128,
                        SocketFlags.None, new AsyncCallback(OnDataReceived), packet);
    

    And in callback, here is caught timeout SocketException, which raises when socket doesn't get ACK signal after keep-alive packet.

    public void OnDataReceived(IAsyncResult asyn)
    {
        try
        {
            SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
    
            int iRx = socket.EndReceive(asyn);
        }
        catch (SocketException ex)
        {
            SocketExceptionCaught(ex);
        }
    }
    

    This way, I'm able to safely detect disconnection between TCP client and server.

提交回复
热议问题