我写与升压一个UDP服务器应用程序,应在插座上听5秒,如果没有数据包已经被这5秒内收到,请继续做其他事情。的std ::未来加速UDP套接字不工作异步接收操作
通过some answers的启发,我决定尝试基于的std ::未来的解决方案。
的问题是,调用wait_for()
总是超时,就好像没有收到数据。但是,如果我在超时后执行的行上设置断点,并且检查变量,我会看到缓冲区包含收到的数据报,并且对象包含客户端的地址。换句话说,套接字接收按预期工作,但std :: future不会触发。为什么?
这里是我的测试服务器代码:
#include <future>
#include <boost/asio.hpp>
#include <boost/asio/use_future.hpp>
using boost::asio::ip::udp;
int main()
{
try
{
boost::asio::io_service io_service;
udp::socket socket(io_service, udp::endpoint(udp::v4(), 10000));
char recv_buf[8];
for (;;)
{
ZeroMemory(recv_buf, 8);
udp::endpoint remote_endpoint;
std::future<std::size_t> recv_length;
recv_length = socket.async_receive_from(
boost::asio::buffer(recv_buf),
remote_endpoint,
0,
boost::asio::use_future);
if (recv_length.wait_for(
std::chrono::seconds(5)) == std::future_status::timeout)
{
printf("time out. Nothing received.\n");
}
else
{
printf("received something: %s\n", recv_buf);
}
}
}
catch (std::exception& e)
{
printf("Error: %s\n", e.what());
}
return 0;
}
我一直在敲打我的头就这一个了一段时间,所以任何帮助,将不胜感激。我在Windows 10使用Visual Studio 2015年
这里是我的测试客户端代码(在python,抱歉)。
import socket
import time
HOST = "server" # The remote host
PORT = 10000 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
address = socket.getaddrinfo(HOST, PORT)[0][-1]
while True:
s.sendto("ping\0", address)
time.sleep(1)
链接的问题和答案提到需要运行'io_service':“与调用线程将被阻塞,等待未来,至少一个其他线程必须处理'io_service'允许异步[... ]行动来实现和履行承诺。“ –