When the client and the server communicate through TCP socket, if the client application Exits normally or unexpectedly, the server will get awareness on the corresponding connection (for example, return 0 or throw an exception ). However, if the client's network cable is unplugged, it will take two hours for the server to detect a disconnection from the client by default. For many server applications, such a long response time is intolerable.
We usually use the heartbeat mechanism at the application layer to solve similar problems. This is feasible.
However, we can use the heartbeat mechanism of the socket to solve this problem. System. net. sockets. Socket provides the iocontrol () method to set parameters related to the sokect heartbeat mechanism. For example, we set the keepalive time to 20 seconds and the check interval to 2 seconds. You can do this: int keepalive =-1744830460; // sio_keepalive_vals
Byte [] invalue = new byte [] {1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 }; // true, 20 seconds, 2 seconds
Sock. iocontrol (keepalive, invalue, null );
The hexadecimal representation of 20 seconds (20000 milliseconds) is 4e20, And the hexadecimal representation of 2 seconds (2000 milliseconds) is 07d0, you can modify the invalue parameter to the desired value.
In the above settings, if the client network cable is dropped, the server socket. receive () will throw an exception in 20 seconds (note that during these 20 seconds, the server will not throw an exception whether it is receiving messages from the socket or sending messages !).