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 disconnected, the server will not detect the client's disconnection until two hours by default. For many server applications Program For example, 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, here, we can use the socket heartbeat mechanism 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 !).
From:
Http://www.cnblogs.com/zhuweisky/archive/2007/05/28/762742.html