Notes How to determine the client socket disconnection in a Linux server

Source: Internet
Author: User

Here's a list of ways to judge if the remote has been disconnected: (from http://blog.csdn.net/god2469/article/details/8801356)

Law One:

When the recv () return value is less than or equal to 0 o'clock, the socket connection is broken. But also need to determine whether errno equals eintr, if errno = = Eintr that the recv function is because the program received the signal returned, the socket connection is normal, should not close the socket connection.

Law II:

struct Tcp_info info;
int len=sizeof (info);
GetSockOpt (sock, Ipproto_tcp, Tcp_info, &info, (socklen_t *) &len);
if ((info.tcpi_state==tcp_established)) indicates that the else fracture is not disconnected

Fahsarm

If a system function such as SELECT is used, if the remote disconnects, select returns 1,RECV returns 0 to disconnect. Other considerations are the same as law I.

Law IV:

int keepAlive = 1; Turn on the KeepAlive property
int keepidle = 60; If the connection does not have any data in 60 seconds, the probe
int keepinterval = 5; The time interval for the packet to be detected is 5 seconds
int keepcount = 3; The number of attempts to probe. If the 1th probe packet receives a response, it will not be sent 2 times.

SetSockOpt (RS, Sol_socket, so_keepalive, (void *) &keepalive, sizeof (KEEPALIVE));
SetSockOpt (RS, Sol_tcp, Tcp_keepidle, (void*) &keepidle, sizeof (Keepidle));
SetSockOpt (RS, Sol_tcp, TCP_KEEPINTVL, (void *) &keepinterval, sizeof (Keepinterval));
SetSockOpt (RS, Sol_tcp, tcp_keepcnt, (void *) &keepcount, sizeof (Keepcount));

When set, if disconnected, fails immediately when using the socket to read and write, and returns a etimedout error

Law V:

Self-realization of a heartbeat detection, not received within a certain time the custom heartbeat package is marked as disconnected.

Notes How to determine the client socket disconnection in a Linux server

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.