简体   繁体   English

用于阻止连接的c ++ boost asio timeout

[英]c++ boost asio timeout for blocking connect

I have a C++ boost client that does a blocking connect and processes the message once it receives a response. 我有一个C ++ boost客户端,它执行阻塞连接并在收到响应后处理该消息。 I am facing a strange issue. 我面临一个奇怪的问题。

tcp::resolver::query query(tcp::v6(), this->host, port,tcp::resolver::query::v4_mapped);
iterator = resolver.resolve(query);
socket = new tcp::socket(io_service);
socket->connect(*iterator);

I tried to connect to a machine that was not reachable by ping6 (but was IPV6 enabled). 我试图连接到ping6无法访问的计算机(但启用了IPV6)。 Still, I didn't get any error while trying to resolve the query in line-2. 尽管如此,我在尝试解决第2行中的查询时没有收到任何错误。 As a result of this, it takes too much time while attempting a connection before giving an error. 因此,在发出错误之前尝试连接需要花费太多时间。 My questions:- 我的问题: -

1) Is it possible to timeout on a blocking connect from asio? 1)是否可以在asio的阻塞连接上超时? I cannot switch to async mode of operation. 我无法切换到异步操作模式。

2) How come I don't get an error while it resolves an unreachable host? 2)为什么在解析无法访问的主机时我没有收到错误?

Any advice would be very much helpful 任何建议都会非常有用

Timeouts are the wrong place for synchronous methods, there's a lengthy discussion in the asio ticket tracker. 超时是同步方法的错误位置,在asio票据跟踪器中进行了长时间的讨论

I cannot switch to async mode of operation. 我无法切换到异步操作模式。

I find this highly unlikely given the timeout requirement, post the rest of your code and explain why you cannot use asynchronous operations. 鉴于超时要求,我发现这很不可能,发布其余代码并解释为什么不能使用异步操作。

When this question was asked, I guess ASIO did not have any example on how to accomplish what the OP needed, that is to timeout a blocking operation such as a blocking socket operation. 当问到这个问题时,我猜ASIO没有任何关于如何完成所需OP的例子,即超时阻塞操作,例如阻塞套接字操作。 Now there exists examples to show you exactly how to do this. 现在有一些示例可以向您展示如何执行此操作。 the example seems long, but that is because it is WELL commented. 这个例子似乎很长,但那是因为它得到了很好的评论。 It shows how to use the ioservice in a 'one shot' kind of mode. 它展示了如何在“一次性”模式中使用ioservice。

I think the example is a great solution. 我认为这个例子是一个很好的解决方案。 The other solutions here break portability and don't take advantage of ioservice. 这里的其他解决方案打破了可移植性,并没有利用ioservice。 if portability is not important and the ioservice seems like to much overhead --THEN-- you should not be using ASIO. 如果可移植性不重要且ioservice似乎要花费很多--THEN--你不应该使用ASIO。 No matter what, you will have an ioservice created (almost all ASIO functionality depends on it, even sync sockets) so, take advantage of it. 无论如何,你都会创建一个ioservice(几乎所有的ASIO功能都依赖于它,甚至同步套接字),所以,利用它。

ASIO example of timeout on blocking call 阻止呼叫超时的ASIO示例

The ASIO documentation has been updated, so check it out for new examples on how to overcome some of the 'gotchas' ASIO use to have. ASIO文档已经更新,因此请查看有关如何克服ASIO使用的“陷阱”的新示例。

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

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