我正在尝试 boost 示例中的示例异步和同步 UDP 服务器示例。
boost版本是1.84.0,Visual Studio 2019。
代码编译,netstat 显示服务器正在侦听正确的端口。 Wireshark 显示 UDP 客户端正在向 UDP 端口发送数据,但函数 socket.receive_from() 之后的任何断点或异步示例的回调都没有显示接收数据成功。
大家有什么想法吗?
#include <array>
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
int main()
{
try
{
boost::asio::io_context io_context;
udp::socket socket(io_context, udp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 8080));
time_t now = time(NULL);
//char *str = ctime(&now);
char str[26] = {};
ctime_s(str, 26, &now);
for (;;)
{
std::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
socket.receive_from(boost::asio::buffer(recv_buf), remote_endpoint);
std::string message = std::string(str);
boost::system::error_code ignored_error;
socket.send_to(boost::asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
检查防火墙、不同的目标 IP 地址或(虚拟)网络适配器。
要排除后者,您可以首先不绑定特定地址(127.0.0.1):
udp::socket socket(io_context, {{}, 8080});
对于其余的事情,我非常希望它能够发挥作用。添加更多交互,在 Linux 上演示(抱歉没有可用的 Windows):
#include <array>
#include <boost/asio.hpp>
#include <ctime>
#include <iostream>
#include <string>
namespace asio = boost::asio;
using asio::ip::udp;
int main() {
try {
asio::io_context io_context;
udp::socket socket(io_context, {{}, 8080});
char str[26] = {};
std::array<char, 1024> recv_buf;
for (;;) {
udp::endpoint sender;
auto n = socket.receive_from(asio::buffer(recv_buf), sender);
std::string_view msg(recv_buf.data(), n);
if (size_t pos; -1ull != (pos = msg.find_last_not_of(" \n\r\t\f")))
msg = msg.substr(0, pos + 1);
std::cout << "Received " << quoted(msg) << " from " << sender << std::endl;
time_t now = time(NULL);
ctime_r(&now, str);
boost::system::error_code ignored_error;
socket.send_to(asio::buffer(std::string_view(str)), sender, 0, ignored_error);
}
} catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
}
}
在本地进行演示,有 20 个并发客户端,每个客户端不断发送 5 条消息:
function stream() { while sleep .1; do echo "message $RANDOM"; done; }
function clients() { split -ul 5 --filter='nc -Nuq0 localhost 8080';
for a in {1..20}; do (stream | clients)& done; sleep 10; killall nc