简体   繁体   English

当连接失败时,Boost ASIO ip tcp iostream expires_from_now不会导致错误

[英]Boost ASIO ip tcp iostream expires_from_now doesn't result in an error when connection fails

We've come across a strange situation where our code reports that it has successfully opened a connection to an unreachable address. 我们遇到了一种奇怪的情况,我们的代码报告说它已成功打开了到不可达地址的连接。 But it only happens when we actively reduce the time-out for a boost::asio::ip::tcp::iostream : 但是只有当我们积极减少boost::asio::ip::tcp::iostream的超时时,才会发生这种情况:

void Connect(std::string address, std::string port) {
    std::cout << "Waiting to connect: " << address << " at port " << port << "\n";
    boost::asio::ip::tcp::iostream s;

    s.expires_from_now(std::chrono::seconds(5));
    s.connect(address, port);

    if (!s) {
        std::cout << "Unable to connect: " << s.error().message() << "\n";
    } else {
        std::cout << "Success!" << "\n";
    }              
}

With the above code, connect("192.168.25.25", "1234"); 使用上面的代码, connect("192.168.25.25", "1234"); will quickly report "Success!", even though the address is unreachable. 即使该地址无法访问,也会迅速报告“成功!”。 If we remove the expires_from_now , then we instead get "Unable to connect: Connection timed out" after about 2 minutes - as we expect. 如果我们删除expires_from_now ,那么大约2分钟后就会收到“无法连接:连接超时”的提示-正如我们所期望的那样。

I would have expected that changing the timeout using expires_from_now would result in a time-out error state. 我曾期望使用expires_from_now更改超时将导致超时错误状态。 We're using boost 1.68. 我们正在使用增强1.68。

Is there any other way to find out that the time-out is reached, or perhaps more appropriately, whether the connection has been established? 还有其他方法可以确定是否已达到超时,或者更合适的是,是否已建立连接?

The "Success" indication just means that nothing has gone wrong yet. “成功”指示仅表示没有任何问题。 It does not mean that the connect has succeeded. 并不意味着connect成功。 You chose not to wait to find out whether the connect succeeded or failed and to instead time out the wait for that result. 您选择不等待以确定连接是成功还是失败,而是等待该结果超时。

You cannot make a TCP connect operation fail early. 您不能使TCP连接操作尽早失败。 The rules for the conditions under which a TCP connect attempt fails are part of the TCP specification and just setting a timeout won't change how long it takes the connection attempt to fail. TCP连接尝试失败的条件规则是TCP规范的一部分,仅设置超时不会更改连接尝试失败的时间。

Querying for the remote_endpoint will however indicate an error condition if the connection has not been established, for example: 但是,如果尚未建立连接,则查询remote_endpoint将指示错误情况,例如:

boost::system::error_code ec;
s.socket().remote_endpoint(ec);
if (ec)
{
    std::cout << "Unable to connect\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM