使用 boost asio 区分客户
Differentiate clients using boost asio
如何区分使用 boost.asio 和 UDP 的客户端,其中所有提升示例都使用成员变量一次保存一个远程端点。我需要保存一个端点列表,并确定在接收到的数据到达时将其发送到哪个对象。我目前有这样的代码
void Receive() {
boost::asio::ip::udp::endpoint client_endpoint;
char data[32];
socket_.async_receive_from(boost::asio::buffer(data, 32), client_endpoint,
boost::bind(&MyClass::onReceive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
但是 client_endpoint
将超出处理程序函数的范围(不可用),如果这是我第一次收到来自它们,或者更新适当的客户端对象(如果不是)。
我正在考虑将 std::set<boost::ip::udp::endpoint> client_sessions_;
作为我的服务器的成员变量,但是 client_endpoint
在异步调用被调度之前仍然没有被填充。
我该如何处理?
您可以在 shared_ptr 中保留您的端点。此外,你有 asio::buffer 的错误 - async_receive_from 将写入已经退出的函数堆栈,可能会损坏堆栈。正确的片段应该是这样的:
void Receive() {
auto client_endpoint = std::make_shared<boost::asio::ip::udp::endpoint>();
std::shared_ptr<char> data(new char[32], std::default_delete<char[]>());
socket_.async_receive_from(boost::asio::buffer(data.get(), 32), *client_endpoint,
boost::bind(&MyClass::onReceive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, data, client_endpoint));
}
//...
void MyClass::onReceive(boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, std::shared_ptr<char> data, std::shared_ptr<boost::asio::ip::udp::endpoint> client_endpoint);
或者为了简单起见,您可以使用 new/delete(不太推荐)
如何区分使用 boost.asio 和 UDP 的客户端,其中所有提升示例都使用成员变量一次保存一个远程端点。我需要保存一个端点列表,并确定在接收到的数据到达时将其发送到哪个对象。我目前有这样的代码
void Receive() {
boost::asio::ip::udp::endpoint client_endpoint;
char data[32];
socket_.async_receive_from(boost::asio::buffer(data, 32), client_endpoint,
boost::bind(&MyClass::onReceive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
但是 client_endpoint
将超出处理程序函数的范围(不可用),如果这是我第一次收到来自它们,或者更新适当的客户端对象(如果不是)。
我正在考虑将 std::set<boost::ip::udp::endpoint> client_sessions_;
作为我的服务器的成员变量,但是 client_endpoint
在异步调用被调度之前仍然没有被填充。
我该如何处理?
您可以在 shared_ptr 中保留您的端点。此外,你有 asio::buffer 的错误 - async_receive_from 将写入已经退出的函数堆栈,可能会损坏堆栈。正确的片段应该是这样的:
void Receive() {
auto client_endpoint = std::make_shared<boost::asio::ip::udp::endpoint>();
std::shared_ptr<char> data(new char[32], std::default_delete<char[]>());
socket_.async_receive_from(boost::asio::buffer(data.get(), 32), *client_endpoint,
boost::bind(&MyClass::onReceive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, data, client_endpoint));
}
//...
void MyClass::onReceive(boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, std::shared_ptr<char> data, std::shared_ptr<boost::asio::ip::udp::endpoint> client_endpoint);
或者为了简单起见,您可以使用 new/delete(不太推荐)