0x0000eWan
0x0000eWan

Reputation: 307

C++ - detecting dead sockets

I have a server application written in C++. When a client connects, it creates a new thread for him. In that thread there is a BLOCKING reading from a socket. Because there is a possibility for a client to accidentally disconnect and left behind a thread still hanging on the read function, there is a thread that checks if the sockets are still alive by sending "heartbeat messages". The message consists of 1 character and is "ignored" by the client (it is not processed like other messages). The write looks like this:

write(fd, ";", 1);

It works fine, but is it really necessary to send a random character through the socket? I tried to send an empty message ("" with length 0), but it didn't work. Is there any better way to solve this socket checking?

Edit:

I'm using BSD sockets (TCP).

Upvotes: 2

Views: 2096

Answers (3)

mark
mark

Reputation: 5449

In my experience, using heartbeat messages on TCP (and checking for responses, e.g. NOP/NOP-ACK) is the easiest way to get reliable and timely indication of connectivity at the application layer. The network layer can do some interesting things but getting notification in your application can be tricky.

If you can switch to UDP, you'll have more control and flexibility at the application layer, and probably reduced traffic overall since you can customize the communications, but you'll need to handle reliability, packet ordering, etc. yourself.

Upvotes: 2

shijie xu
shijie xu

Reputation: 2097

You can set connection KEEPALIVE. You may have interests in this link: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html

It is ok you create a thread for each new coming requests if it is only toy. In most of time, i use poll, that is non-blocking io, for performance improvement.

Upvotes: 1

Sam
Sam

Reputation: 2969

I'm assuming when you say, "socket, you mean a TCP network socket.

If that's true, then the TCP protocol gives you a keepalive option that you would need to ask the OS to use.

I think this StackOverflow answer gets at what you would need to do, assuming a BSDish socket library.

Upvotes: 2

Related Questions