[英]Is this real scenario using boost::asio for full duplex communication?
[英]boost::asio full duplex connection
我正在使用boost :: asio编写一个相当简单的服务器。
如果要独立读取和写入套接字,该如何设置boost :: asio async_write()和async_read_some()方法?
大多数boost示例都具有async_accept()调用,该调用绑定到处理程序,该处理程序最终调用async_write()或async_read(),但不能同时调用两者。
建立连接后,我仅直接启动async_read_some()。 在回调期间,我处理收到的数据,然后再次启动async_read_some()。
对于写部分:只要有第一个要写入的数据包,我就会立即调用async_write。 当写入一个数据包时,不能再写入其他数据,因此我也使用队列来写入数据。
一些伪代码:
Connection::sendBytes(bytes)
{
if (!sendInProgress) {
socket->async_write_some(bytes, onMessageWritten);
sendInProgress = true;
}
else writeQueue.push_back(bytes);
}
Connection::onBytesWritten()
{
if (writeQueue.size() == 0) {
sendInProgress = false;
}
else {
// Here you can theoretically send all left data at once (using vectored IO) or only some of the data.
// Depending on data size performance will be different.
socket->async_write_some(writeQueue, onBytesWritten);
writeQueue.clear();
}
}
另外,您将需要一些错误处理,并且取决于谁可以调用write方法并锁定。 如果您只从驱动io_service的单个线程中进行写调用,那么这会容易得多,因为所有读和写都在同一线程中发生(事件循环),并且您不会锁定。 例如,如果您在onBytesReceived处理程序中调用sendBytes,就会是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.