本文旨在讲述muduo网络库数据的发送流程。
首先明确一点,Muduo中的epoll使用了水平触发方式,而不是边缘触发。
TcpConnection首先需要增加应用层的缓冲区
Buffer outputBuffer_;
我们看到在TcpConnection类内,提供了两个数据发送函数,分别是TcpConnection::send,TcpConnection::sendInLoop。前者也是调用后者,保证数据的发送在IO线程内的EventLoop执行。(本博客系列都是基于Muduo的示例教程代码分析,个人认为这样更能理解整个网络库的整体流程)
void TcpConnection::send(const std::string& message)
{
if (state_ == kConnected) {
if (loop_->isInLoopThread()) {
sendInLoop(message);
} else {
loop_->runInLoop(
boost::bind(&TcpConnection::sendInLoop, this, message));
}
}
}
void TcpConnection::sendInLoop(const std::string& message)
{
loop_->assertInLoopThread();
ssize_t nwrote = 0;
// if no thing in output queue, try writing directly
//如果channel没有在写,并且buffer没有数据
if (!channel_->isWriting() && outputBuf