【发布时间】:2018-02-07 21:29:14
【问题描述】:
我正在尝试使用 Boost 库创建一个简单的异步接收器。我按照示例和书籍进行操作,到目前为止,这是我能够做到的:
class networkUDPClient {
public:
utilityTripleBuffer * buffer;
char testBuffer[20] = { 0 };
const char * hostAddress;
unsigned int port;
boost::asio::io_service service;
boost::asio::ip::udp::socket socket;
boost::asio::ip::udp::endpoint listenerEndpoint;
boost::asio::ip::udp::endpoint senderEndpoint;
// Function Definitions
void readCallback(const boost::system::error_code & err, std::size_t read_bytes) {
}
// Constructors
networkUDPClient(const char * hostAddress, unsigned int port, unsigned int bufferSize) :
socket(service),
listenerEndpoint(boost::asio::ip::address_v4::from_string(hostAddress), port)
{
this->buffer = new utilityTripleBuffer(bufferSize, nullptr);
this->hostAddress = hostAddress;
this->port = port;
socket.open(this->listenerEndpoint.protocol());
socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket.bind(this->listenerEndpoint);
socket.async_receive_from(boost::asio::buffer(this->buffer->currentBufferAddr, this->buffer->bufferSize), 0, senderEndpoint, readCallback);
service.run();
};
~networkUDPClient()
{
service.stop();
delete this->buffer;
};
};
问题是 async_receive_from 函数导致错误:
严重性代码描述项目文件行抑制状态 错误(活动)没有重载函数实例“boost::asio::basic_datagram_socket::async_receive_from [with Protocol=boost::asio::ip::udp, DatagramSocketService=boost::asio::datagram_socket_service
我仔细检查了参考网站以及我所有的书籍,我相信我传递了正确的参数并正确初始化它们。什么可能导致问题?
额外问题:
虽然我在这里,但我想知道在这种情况下使用动态指针是否可以接受。我需要对收到的数据进行双重缓冲,以便给自己一些时间来处理前一帧。在这种情况下, this->buffer->currentBufferAddr 每次接收数据后都会发生变化,每次都指向不同的缓冲区。
这是一种可以接受的做事方式吗?
【问题讨论】:
-
尝试回调
static void readCallback还是使用bind绑定this?问题中的错误信息不完整 -
传递
boost::bind(&networkUDPClient::readCallback, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred而不仅仅是readCallback -
错误消息正是 Visual Studio 为我提供的。我想知道为什么需要绑定函数,而所有的例子(包括 Torjo 书)都不需要。
-
非静态成员函数有一个 hidden
this参数,但处理程序原型没有这样的参数。所以你只能传递普通函数、静态成员函数或 lambda。否则,您必须将第一个参数绑定到 this 并获取一个仅需要 2 个参数的函数。 -
我没有使用
boost::asio的经验,无法回答额外问题,没有进一步研究 :) 很高兴我能提供帮助
标签: c++ boost boost-asio