【发布时间】:2016-11-23 21:49:25
【问题描述】:
我正在使用 Boost 编写一个 UDP 服务器应用程序,它应该在套接字上侦听 5 秒,如果在这 5 秒内没有收到数据报,则继续做其他事情。
受到some answers的启发,我决定尝试基于std::future的解决方案。
问题是对wait_for() 的调用总是超时,就好像没有收到数据一样。但是,如果我在超时后执行的行上设置断点并检查变量,我会看到缓冲区包含接收到的数据报,remote_endpoint 对象包含客户端的地址。换句话说,套接字接收按预期工作,但 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;
}
我一直在努力解决这个问题,因此我们将不胜感激。我在装有 Visual Studio 2015 的 Windows 10 上。
这是我的测试客户端代码(在 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以允许async [...] 操作来推进和履行承诺。”
标签: c++ boost udp boost-asio future