Boost asio-acceptor 在没有新连接的情况下解锁?
我正在使用 C++ boost asio 库,在其中监听套接字上的新连接。获得连接后,我处理请求,然后循环监听另一个套接字上的新连接。
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();
}
}
根据我的理解,它应该始终阻塞在 this->blitzAcceptor.accept(soc,ec); 并且每次建立新连接时,它都应该在 this->HandleRequest( soc); 并再次阻塞在 this->blitzAcceptor.accept(soc,ec);
但我看到的是,它第一次会阻塞在this->blitzAcceptor.accept(soc,ec) 当建立新连接时,它将处理请求,但不会再次阻塞 this->blitzAcceptor.accept(soc ,ec) 它将继续进入 this->HandleRequest(soc); 并在 soc.receive(); 内部阻塞。
这种情况并不总是发生,但大多数时候都会发生。这种行为的原因可能是什么,以及如何确保它始终在 this->blitzAcceptor.accept(soc,ec) 处阻塞,直到发出新请求?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

此行为完全取决于客户端代码。如果它连接了,但没有发送请求,服务器在接收数据时会阻塞。
你不能。但是您的服务器可以启动超时,该超时在接受连接后立即开始。如果客户端在该时间内没有发送请求,则关闭套接字。为此,您应该改用异步方法而不是同步方法。
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.