简体   繁体   中英

boost::asio full duplex connection

I'm writing a fairly simple server using boost::asio.

How do you go about setting up the boost::asio async_write() and async_read_some() methods for the case where you are reading and writing to a socket independently?

Most of the boost examples have an async_accept() call which binds to a handler which ends up calling either async_write() or async_read() but not both.

I start only async_read_some() directly after the connection was established. During the callback I process the received data and then start async_read_some() again.

For the write part: I'm calling async_write as soon as there is the first data packet to write. While one packet is written no other data can be written, therefore I also use a queue for data to write.

Some pseudo code:

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();
  }
}

Additionally you will need some error handling and depending on who can call the write methods also locking. If you only do write calls from within a single thread which is driving the io_service then this is much easier because then all reads and writes happen in the same thread (event loop) and you don't locking. Eg this would be the case if you call sendBytes in your onBytesReceived handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM