A summary of the heartbeat mechanism of Linux socket programming

Source: Internet
Author: User
Tags set socket

A summary of the heartbeat mechanism of Linux socket programming

The purpose of my writing this article is to summarize the use of the heartbeat mechanism, because the last two items of TCP communication have used this method, feel the use of good poetry is more classic, so take it out to share with you.

What is the heartbeat mechanism

heartbeat mechanism is when the client and the server to establish a connection, every few minutes to send a fixed message to the server, the server received a fixed message to the client, if the server does not receive a client message within a few minutes, the client is considered disconnected. The sender can be the client and the server to see the specific requirements.

Why to use

We all know that in the case of TCP such a long connection, there may be a large period of time is no data exchange, that is, in an idle state. Theoretically, this connection is always connected, but in practical applications, it is difficult to predict what is wrong with the intermediate node. Even more frightening is that some nodes will automatically cut off the connection without data interaction for a certain period of time. Therefore, we need to use the heartbeat mechanism to maintain long-connected, keepalive communication.

Implementation method


    • Application layer: by the application itself at a certain time to the client/server to send a short packet, and then start a thread, the threads constantly detect the response of the client, if not received a customer/server response within a certain time, that is, the customer/service side has been dropped, the connection is not available.
    • set so_keepalive socket options: in TCP communication, there is a heartbeat mechanism. is actually the TCP option. When the service/client opens the KeepAlive function, it will automatically send the heartbeat packet to the other party within the specified time, and the other side will automatically reply after receiving the heartbeat packet to tell the other party that I am still online.

Note: because the KeepAlive feature requires additional bandwidth and traffic, the TCP protocol layer does not turn on keepalive by default. The KeepAlive timeout requires 7,200,000 MilliSeconds, which is 2 hours, and the number of probes is 5 times. For many applications, the idle time is too long. Therefore, we can manually turn on the KeepAlive function and set reasonable keepalive parameters.
My implementation

This method of setting the SO_KEEPALIVE socket option is specifically described here.

Three parameters of So_keepalive:
    1. TCP_KEEPALIVE_INTVL: Probe packet interval is INTVL.
    2. Tcp_keepalive_idle: The connection does not have any data in idle time, then this TCP layer is probed.
    3. TCP_KEEPALIVE_CNT: Number of attempts to probe.
SetSockOpt () function Introduction
    1. Usage: Sets the options associated with a socket. Options may exist in multi-tier protocols, and they will always appear on the topmost socket layer.
    2. Function Prototypes:
#include <sys/types.h>#include <sys/socket.h>int setsockopt(intSockintLevelintoptname, const void*optval, socklen_t Optlen); parameter: Sock: The socket that will be set or gets the option. Level: The protocol layer where the option is located. Optname: The name of the option that needs to be accessed. Optval: Forgetsockopt() that points to the buffer that returns the value of the option. Forsetsockopt(), pointing to the buffer that contains the new option value. Optlen: Forgetsockopt(), as the entry parameter, the maximum length of the option value. The actual length of the option value as an exit parameter. Forsetsockopt(), the length of the current option. Return Description: When executed successfully, returns0。 Failed to return-1, errno is set to one of the following values Ebadf:sock is not a valid file descriptor Efault:optval The memory pointed to is not a valid process space einval: in the callsetsockopt(), Optlen invalid enoprotoopt: The specified protocol layer does not recognize the option Enotsock:sock describes the socket
Specific code
intHeartbeatintFD) {intAlive,error,idle,cnt,intv;/ * Open keepalive on FD */Restart:alive =1;//setKeepAliveOpenret=setsockopt(Fd,sol_socket,so_keepalive,&alive,sizeof (Alive));if(Ret <0) {DEBUG ("Set socket option error.\n");GotoRestart; }    /*     * -S without data,SendHeartbeat Package     */Idle = -; RET =setsockopt(Fd,sol_tcp,tcp_keepidle,&idle,sizeof (idle));if(Ret <0) {DEBUG ("Set keepalive idle error.\n");return-1; }/* * without any respond,3mLater resend Package     */Intv = the; RET =setsockopt(Fd,sol_tcp,tcp_keepintvl,&intv,sizeof (INTV));if(Ret <0) {DEBUG ("Set keepalive intv error.\n");return-2; }    /*     *Send 5  Times, without any Response,meanConnectLose*/CNT =5; RET =setsockopt(Fd,sol_tcp,tcp_keepcnt,&cnt,sizeof (CNT));if(Ret <0) {DEBUG ("Set keepalive cnt error.\n");return-3; }}

Note: Debug in code is a debug macro that I have defined for myself, see https://github.com/AnSwErYWJ/DogFood/blob/master/debug.c for details. or http://blog.csdn.net/u011192270/article/details/47618225.

Summarize

There are, of course, many ways to implement the heartbeat mechanism, such as the time-out control implemented with select, or the individual detection of the daemon or thread. However, I personally think that setting up so_keepalive is the simplest and most convenient to implement. If you find any problems, we also welcome you to communicate.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A summary of the heartbeat mechanism of Linux socket programming

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.