Remember that the client initiates the connection, so you only need to restore the socket and accept it again. I will keep the format of your snippet, but I hope that your real code will be encapsulated correctly.
using SocketType = boost::asio::ip::tcp::socket; std::unique_ptr<SocketType> CreateSocketAndAccept( boost::asio::io_service& io_service, boost::asio::ip::tcp::acceptor& acceptor) { auto socket = std::make_unique<boost::asio::ip::tcp::socket>(io_service); boost::system::error_code ec; acceptor.accept(*socket.get(), ec); if (ec) { //TODO: Add handler. } return socket; } ... auto socket = CreateSocketAndAccept(IOservice, acceptor); for (;;) { boost::system::error_code ec; auto len = boost::asio::read_until(*socket.get(), sbuf, end, ec); if (ec) // you could be more picky here of course, // eg check against connection_reset, connection_aborted socket = CreateSocketAndAccept(IOservice, acceptor); ... }
Footnote: Unless, of course, the socket must remain in scope.
Edit: based on the comments below.
The auditory socket itself does not know if the client is silent or disconnected. All operations, especially synchronous ones, must impose a restriction on completion. Consider setting SO_RCVTIMEO or SO_KEEPALIVE (for each socket or the whole system for more information. How to use the SO_KEEPALIVE parameter correctly to find that the client is not working from the other end? ).
Another option is to switch to async and implement a full-fledged “common” socket server (the example of the BOOST page is a great start).
In any case, you may run into data consistency problems and be forced to deal with it, for example. when the client detects an interrupted connection, it will resend the data. (or something more complicated using higher level protocols)
source share