How to check if socket is closed in Boost.Asio?

19,390

Solution 1

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.

Solution 2

Just check for boost::asio::error::eof error in your async_receive handler. It means the connection has been closed. That's the only proper way to do this.

Solution 3

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.

Solution 4

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.

Share:
19,390

Related videos on Youtube

Hali
Author by

Hali

Web developer, mostly focusing on PHP/Laravel and React. Also fluent in C# and Java, and have some experience in 2D game dev, and creating programming languages - generating parsers/lexers, implementing AST/bytecode interpreters.

Updated on June 04, 2022

Comments

  • Hali
    Hali almost 2 years

    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).

  • Hali
    Hali almost 15 years
    ...and I need to read to get the EOF. I guess there's no way around then. Thanks!
  • Admin
    Admin about 12 years
    suppose you have setup the socket and response then you can setup a stream e.g. std::istream myhttpstream(&presponse); and then you can use the std::istream::peek() function .
  • Chuck D
    Chuck D over 6 years
    I do this: received = socket().receive(boost::asio::buffer(buf), tcp::socket::message_peek);
  • John
    John over 2 years
    I can't see there is any relation between "start reading it inmediately and never stop doing so" and "making your server or client to support both synchronous and asynchronous protocols". Could you please explain that in more detail for me?

Related