-1

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.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • did you try placing try & catch blocks ? – Shmil The Cat Mar 15 '13 at 23:46
  • Did, but I don't know what is the name of exception type name, so I don't know what to place within `catch()` as paramater. I failed to find this in docs and IDE does not give me any hints here. – Tomáš Zato Mar 15 '13 at 23:49
  • @TomášZato all sane libraries should derive their exceptions from `std::exception` -- even if I don't actually use boost I believe it is sane enough to respect that convention. And anyway the effing' manual should have the precise answer. ;) At worst, your debugger should tell you the exception type. – syam Mar 15 '13 at 23:58
  • While many Boost.Asio calls can throw, the majority of them also provide an overload that will not throw. For example, [this](http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_stream_socket/receive/overload3.html) overload for `socket::receive()` could be used instead of try/catch. – Tanner Sansbury Mar 16 '13 at 03:16

1 Answers1

3
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 :)

Shmil The Cat
  • 4,548
  • 2
  • 28
  • 37
  • Unfortunatelly, that will not work. `'eof' : the name of a function parameter cannot be qualified` - this error makes no sense to me, but IDE just says that `boost::asio::error::eof` is not a type name. – Tomáš Zato Mar 16 '13 at 00:11
  • Oh it is just your wrong interpretation. `boost::system::system_error` is the arror data type, `boost::asio::error::eof` is constant of end of stream error. – Tomáš Zato Mar 16 '13 at 00:13