gpt4 book ai didi

c++ - std::future 在 Boost UDP 套接字异步接收操作中不起作用

转载 作者:行者123 更新时间:2023-11-27 23:58:39 27 4
gpt4 key购买 nike

我正在使用 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 对象的 run 方法。因此 asio 没有运行。请创建一个调用 run 方法的线程,然后重试。

关于c++ - std::future 在 Boost UDP 套接字异步接收操作中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40774699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com