![](/img/trans.png)
[英]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.