I am using the C++ boost asio library, where I listen to new connections on the socket. On getting a connection I process the request and then listen for a new connection on another socket in a loop.
while (true)
{
tcp::socket soc(this->blitzIOService);
this->blitzAcceptor.listen();
boost::system::error_code ec;
this->blitzAcceptor.accept(soc,ec);
if (ec)
{
// Some error occured
cerr << "Error Value: " << ec.value() << endl;
cerr << "Error Message: " << ec.message() << endl;
soc.close();
break;
}
else
{
this->HandleRequest(soc);
soc.shutdown(tcp::socket::shutdown_both);
soc.close();
}
}
According to my understanding it should always block at this->blitzAcceptor.accept(soc,ec); and everytime a new connection is made it should handle it in this->HandleRequest(soc); and again block at this->blitzAcceptor.accept(soc,ec);
But what I see is this that for the first time it will block at this->blitzAcceptor.accept(soc,ec) and when a new connection is made it will handle the request, but instead of blocking again at this->blitzAcceptor.accept(soc,ec) it will go ahead into this->HandleRequest(soc); and block at soc.receive(); inside.
This doesn’t happen always, but happens most of the time. What could be the reason to this behavior, and how can I ensure that it always block at this->blitzAcceptor.accept(soc,ec) until a new request is made?
This behavior is entirely dependent on the client code. If it connects, but does not send a request, the server with block when receiving data.
You can’t. But your server can initiate a timeout that starts immediately after accepting the connection. If the client does not send a request within that duration, close the socket. To do that, you should switch to using asynchronous methods rather than synchronous methods.