且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查Boost :: asio中是否存在套接字连接?

更新时间:2023-11-28 10:07:28

由于底层套接字接口的限制,无法实现isConnected之类的功能来在套接字级别检查TCP连接状态.我想出了一种解决方法.

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.

在我的实现中,我在应用程序中缓存了一个连接状态标志(bool m_IsConnected).该标志用于指定连接状态.它假定如果套接字没有错误,则表明TCP连接处于活动状态.

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仍然为true,因为我们没有获得有关断开连接事件的任何回调.当尝试通过此套接字发送数据时,将出现错误.现在我们知道连接已断开.

The flag will be updated every time when use the socket. If there are errors when send and read data, that means the connection is disconnected. Then change the flag correspondingly. If the TCP connection is idle for a long time. This flag doesn't reflect the actual status of the TCP connection until using the socket. For example, the socket is idle for a long time. It is disconnected due to the poor network. In this case, the m_IsConnected is still true since we don't get any callback regarding the disconnection event. When try to send data through this socket, there will be error. And now we know that the connection is disconnected.