Socket and network disconnection

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.