Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to implement a heartbeat in C++ to check for socket connectivity?

Hey gang. I have just written a client and server in C++ using sys/socket. I need to handle a situation where the client is still active but the server is down. One suggested way to do this is to use a heartbeat to periodically assert connectivity. And if there is none to try to reconnect every X seconds for Y period of time, and then to time out.

Is this "heartbeat" the best way to check for connectivity?

The socket I am using might have information on it, is there a way to check that there is a connection without messing with the buffer?

like image 911
Alex Avatar asked Jan 30 '09 15:01

Alex


People also ask

What is a heartbeat in TCP?

A heartbeat is a type of a communication packet that is sent between nodes. Heartbeats are used to monitor the health of the nodes, networks and network interfaces, and to prevent cluster partitioning.

What is heartbeat timer?

The heartbeat timeout value defines after what period of time the peer TCP connection should be considered unreachable (down) by RabbitMQ and client libraries. This value is negotiated between the client and RabbitMQ server at the time of connection. The client must be configured to request heartbeats.

How long keep TCP connection open?

Keepalive Idle Time If an issue were to occur on an actively used TCP connection, both the client and server would quickly identify errors due to missing ACK packets or even a RST (Reset) from the other side. In general, the default value tcp_keepalive_time is 7200 seconds (2 hours).


1 Answers

If you're using TCP sockets over an IP network, you can use the TCP protocol's keepalive feature, which will periodically check the socket to make sure the other end is still there. (This also has the advantage of keeping the forwarding record for your socket valid in any NAT routers between your client and your server.)

Here's a TCP keepalive overview which outlines some of the reasons you might want to use TCP keepalive; this Linux-specific HOWTO describes how to configure your socket to use TCP keepalive at runtime.

It looks like you can enable TCP keepalive in Windows sockets by setting SIO_KEEPALIVE_VALS using the WSAIoctl() function.

If you're using UDP sockets over IP you'll need to build your own heartbeat into your protocol.

like image 188
Commodore Jaeger Avatar answered Oct 18 '22 15:10

Commodore Jaeger