Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ boost::asio全双工连接_C++_Boost_Boost Asio - Fatal编程技术网

C++ boost::asio全双工连接

C++ boost::asio全双工连接,c++,boost,boost-asio,C++,Boost,Boost Asio,我正在使用boost::asio编写一个相当简单的服务器 对于独立读写套接字的情况,如何设置boost::asio async_write()和async_read_some()方法 大多数boost示例都有一个async_accept()调用,该调用绑定到一个处理程序,该处理程序最终调用async_write()或async_read(),但不能同时调用两者 在建立连接后,我只直接启动async_read_some()。 在回调期间,我处理接收到的数据,然后再次启动async_read_som

我正在使用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();
  }
}
此外,您还需要一些错误处理,这取决于谁可以调用写入方法。如果您只从驱动io_服务的单个线程中写入调用,那么这就容易多了,因为所有读取和写入都发生在同一个线程(事件循环)中,并且您不需要锁定。例如,如果在onBytesReceived处理程序中调用sendBytes,就会出现这种情况