boost :: asio全双工连接

时间:2013-10-08 16:22:30

标签: c++ boost boost-asio

我正在使用boost :: asio编写一个相当简单的服务器。

如何在独立读取和写入套接字的情况下设置boost :: asio async_write()和async_read_some()方法?

大多数boost示例都有一个async_accept()调用,它绑定到一个处理程序,最终调用async_write()或async_read()但不是两者。

1 个答案:

答案 0 :(得分:0)

我在建立连接后直接启动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,就会出现这种情况。

相关问题