如何检查Boost :: asio中是否存在套接字连接? [英] How to check if a socket connection is live in Boost::asio?

查看:230
本文介绍了如何检查Boost :: asio中是否存在套接字连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Boost :: asio来实现客户端/服务器应用程序.下面的客户端代码用于连接到远程服务器.

I'm using the Boost::asio to implement a client/server applicaion. The client code below is used to connect to the remote server .

   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;
    }

在客户端,我想检查连接是否处于活动状态.函数"m_socket.is_open();"不起作用.关闭服务器套接字后,"m_socket.is_open();"在客户端仍然返回true.有什么方法可以检查连接吗?

At the client side, I want to check if the connection is live. The function "m_socket.is_open();" doesn't work. When the server socket is closed, the "m_socket.is_open();" still returns true at client side. Is there any way to check the connection?

推荐答案

由于底层套接字接口的限制,无法实现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.

这篇关于如何检查Boost :: asio中是否存在套接字连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆