asio::async_write 的坑
同一个socket 的async_write操作内部是调用async_write_some 去执行的,在WriteDone之前,如果再次调用async_write 会导致 发送的stream顺序错乱, 典型复现是,
boost::asio::async_write(socket, buffer(xxx, 1024000), yield[ec]); boost::asio::async_write(socket, buffer(buf, 32), std::bind(&Session::write, this, std::placeholders::_1, std::placeholders::_2));
客户端收到的 数据就会乱掉,
解决方案:
添加发送队列就好了
void CAsioSession4S::HandleWriteDone(const boost::system::error_code &ec) { if (this->_sending != nullptr) { delete this->_sending; this->_sending = nullptr; } //error will disconnected if (ec) { while (!_sendQueue.empty()) { delete _sendQueue.front(); _sendQueue.pop(); } this->Disconnect(); return; } //检查发送队列 if (!_sendQueue.empty()) { this->_sending = _sendQueue.front(); _sendQueue.pop(); boost::asio::async_write((*_socket.get()), this->_sending->send, std::bind(&CAsioSession4S::HandleWriteDone, this->shared_from_this(), std::placeholders::_1)); } }