Jef*_*rey 8 c++ boost boost-asio
我正在使用Boost :: asio来实现客户端/服务器应用程序.下面的客户端代码用于连接远程服务器.
try
{
boost::asio::io_service m_io_service;
boost::asio::ip::tcp::socket m_socket(m_io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 17);
m_socket.connect(endpoint);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
在客户端,我想检查连接是否有效.功能" m_socket.is_open();
"不起作用.当服务器套接字关闭时," m_socket.is_open();
"仍然在客户端返回true.有没有办法检查连接?
Due to the limitation of the underlying socket interface, there is no way to implement the function like isConnected to check the TCP connection status at the socket level. I think out a workaround about it.
In my implementation, I cache a connection status flag (bool m_IsConnected
) in my application. This flag is used to designate the connection status. It assumes that if there is no error from socket, the TCP connection is alive.
每次使用套接字时都会更新该标志。如果发送和读取数据时出现错误,则表示连接已断开。然后相应地更改标志。如果 TCP 连接长时间空闲。在使用套接字之前,此标志不会反映 TCP 连接的实际状态。例如,套接字长时间空闲。由于网络不佳,它已断开连接。在这种情况下, m_IsConnected 仍然为真,因为我们没有收到有关断开连接事件的任何回调。当试图通过这个套接字发送数据时,会出现错误。现在我们知道连接已断开。