Lrrr
Lrrr

Reputation: 4805

how to detect tcp client connect to server in c++

I have a tcp client/server, and I want to detect connection loss in client side; because my client have multiple interfaces and at a time I connected to server with one of them, I want to know how to detect connection loss in client side so that I could connect my tcp client with another interface to the server and if all of them are down I store my data in text files. I googled it and I already seen keep alive but it's not what I want.

if it is important my project is in linux and code is in c++.

Upvotes: 0

Views: 2418

Answers (3)

Lrrr
Lrrr

Reputation: 4805

The best way that I found is to check buffer, if buffer is empty it means that your TCP client send the packet to the TCP server successfully and you can send the next packet; for checking the buffer you can use SIOCOUTQ; its very easy to use and show you how much data you have in your buffer.

Upvotes: 1

Serge Ivanoff
Serge Ivanoff

Reputation: 184

TCP connections are designed to be error correcting and not time critical. This error correction includes network timeouts.

Reads and Write will not fail until the socket is actually closed, which may not be for a very long time.

The only way for a client to decide if a connection has timed-out is for the client to detect that it hasn't received any messages for a specified time, and manually close the socket.

That's what Keep Alive messages are for.

Upvotes: 1

mah
mah

Reputation: 39837

Try to read from the socket. When the socket closes, the read will fail, giving you simple detection. You can do this in a dedicated detection thread so that your main thread doesn't block.

Upvotes: 1

Related Questions