views:

1560

answers:

4

What is the easiest way to check if a socket was closed on the remote side of the connection? socket::is_open() returns true even if it is closed on the remote side (I'm using boost::asio::ip::tcp::socket).

I could try to read from the stream and see if it succeeds, but I'd have to change the logic of my program to make it work this way (I do not want data to be extracted from the stream at the point of the check).

+3  A: 

If the connection has been cleanly closed by the peer you should get an EOF while reading. Otherwise I generally ping in order to figure out if the connection is really alive.

Nova
...and I need to read to get the EOF. I guess there's no way around then.Thanks!
Hali
+2  A: 

Is there a boost peek function available? Most socket implementations have a way to read data without removing it from the queue, so you can read it again later. This would seem to satisfy your requirements.

After quickly glancing through the asio docs, I wasn't able to find exactly what I was expecting, but that doesn't mean its not there.

I'd suggest this for starters.

teeks99
Yes, you're right. You can pass a flag to the "receive" method that tells it not remove the data. I was using the "read_some" method, which doesn't have this flag argument. Thanks for pointing it out!
Hali
A: 

I think that in general once you open a socket, you should start reading it inmediately and never stop doing so. This way you can make your server or client to support both synchronous and asynchronous protocols. The moment the client closes the connection, the moment the read will tell you this.

+1  A: 

Using error_code is able to check the condition whether the client is connected or not. If the connection is success, the error_code error.value() will return 0, else return other value. You can also check the message() from the error_code.

Allen