Instantly detect client disconnection from server socket

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

    This is simply not possible. There is no physical connection between you and the server (except in the extremely rare case where you are connecting between two compuers with a loopback cable).

    When the connection is closed gracefully, the other side is notified. But if the connection is disconnected some other way (say the users connection is dropped) then the server won't know until it times out (or tries to write to the connection and the ack times out). That's just the way TCP works and you have to live with it.

    Therefore, "instantly" is unrealistic. The best you can do is within the timeout period, which depends on the platform the code is running on.

    EDIT: If you are only looking for graceful connections, then why not just send a "DISCONNECT" command to the server from your client?

提交回复
热议问题