Search code examples
c++socketsboostboost-asiounhandled-exception

Unhandled exception when reading from disconected socket


I already do know, that it is impossible to simply detect if socket is disconnected or not - the server and clients must shout "Can you hear me?" and "Yeah I can." just like we do on .
But when boost::asio socket is disconnected from other side I obtain Unhanded exception when trying to read from socket. This is kind of disconnect detection useful enough for me. Can I handle that exception, so instead of crashing, the program will produce message in the console?
Some code for those who need it for everything:

bool SocketClient::read(int bytes, char *text) {
      char buffer = 0;
      int length = 0;
      while(bytes>0) {
        size_t len = sock.receive(boost::asio::buffer(&buffer, 1));  //boom: UNHANDLED EXCEPTION
        bytes--;
        text[length] = buffer;
        length++;

      }
      return true;
}

Because I am connecting to minecraft server, I know when the client is disconnected - exception is caused on any read/write attempt.


Solution

  • try
    {
        size_t len = sock.receive(boost::asio::buffer(&buffer, 1));  //boom: UNHANDLED EXCEPTION
        // More code ...
    }
    catch (const boost::system::system_error& ex)
    {
      if ( ex.code() == boost::asio::error::eof ) 
      {
        // Work your magic (console logging, retry , bailout etc.)
      }
    }
    

    Please also take a look at the doc. In the worst case , you could infer the exception type from the debugger :)