在使用Boost.Asio进行UDP通信时,如果遇到"receive_from:错误的文件描述符"错误,可能是由于以下原因导致的:
boost::asio::ip::udp::socket
对象。以下是一个简单的UDP服务器示例,展示了如何使用Boost.Asio接收数据报:
#include <iostream>
#include <boost/asio.hpp>
int main() {
try {
boost::asio::io_context io_context;
boost::asio::ip::udp::socket socket(io_context);
boost::asio::ip::udp::endpoint remote_endpoint;
// 绑定套接字到端点
socket.open(boost::asio::ip::udp::v4());
socket.bind(boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 12345));
while (true) {
char data[1024];
boost::system::error_code error;
// 接收数据报
size_t bytes_transferred = socket.receive_from(
boost::asio::buffer(data), remote_endpoint, 0, error);
if (error) {
std::cerr << "receive_from: " << error.message() << std::endl;
break;
}
std::cout << "Received " << bytes_transferred << " bytes from "
<< remote_endpoint << ": " << std::string(data, bytes_transferred) << std::endl;
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
请确保:
领取专属 10元无门槛券
手把手带您无忧上云