muduo源码分析之TcpConnection

相关文件

muduo/net/TcpConnection.h
muduo/net/TcpConnection.cc

作用

TcpConnection是muduo中一个连接的抽象封装,表示"一次TCP连接"。
TcpConnection没有对外的用户接口,其对象由TcpServer创建。
在TcpServer中,当Acceptor接收新连接,TcpServer在回调函数中创建TcpConnection对象(参数是已经建好连接的socketfd)。
TcpConnection是muduo中最核心最复杂的类,主要包含一个Channel和一个Socket数据成员,即包含读事件、写事件、关闭连接等事件的回调函数。

TcpConnection源码分析

构造函数与连接建立

前面说到当Acceptor接收新连接,TcpServer在回调函数中创建TcpConnection对象(参数是已经建好连接的socketfd。将用户的连接回调函数connCb()注册到TcpConnection中,再通过TcpConnection::connnectEstablished()调用。
image
TcpServer创建TcpConnection设置回调函数:

//TcpServer.cc
void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
{
  loop_->assertInLoopThread();
  EventLoop* ioLoop = threadPool_->getNextLoop();
  char buf[64];
  snprintf(buf, sizeof buf, "-%s#%d", ipPort_.c_str(), nextConnId_);
  ++nextConnId_;
  string connName = name_ + buf;

  LOG_INFO << "TcpServer::newConnection [" << name_
           << "] - new connection [" << connName
           << "] from " << peerAddr.toIpPort();
  InetAddress localAddr(sockets::getLocalAddr(sockfd));
  // FIXME poll with zero timeout to double confirm the new connection
  // FIXME use make_shared if necessary
  TcpConnectionPtr conn(new TcpConnection(ioLoop,
                                          connName,
                                          sockfd,
                                          localAddr,
                                          peerAddr));//引用计数为1,跳出newConnection函数后减一
  connections_[connName] = conn;//引用计数为2
  conn->setConnectionCallback(connectionCallback_);
  conn->setMessageCallback(messageCallback_);
  conn->setWriteCompleteCallback(writeCompleteCallback_);
  conn->setCloseCallback(
      std::bind(&TcpServer::removeConnection, this, _1)); // FIXME: unsafe
  ioLoop->runInLoop(std::bind(&TcpConnection::connectEstablished, conn));//即上面设置的连接回调函数
}

TcpConnection构造函数
在构造函数中设置了自身Channel的回调函数


TcpConnection::TcpConnection(EventLoop* loop,
                             const string& nameArg,
                             int sockfd,
                             const InetAddress& localAddr,
                             const InetAddress& peerAddr)
  : loop_(CHECK_NOTNULL(loop)),
    name_(nameArg),
    state_(kConnecting),
    reading_(true),
    socket_(new Socket(sockfd)),
    channel_(new Channel(loop, sockfd)),
    localAddr_(localAddr),
    peerAddr_(peerAddr),
    highWaterMark_(64*1024*1024)
{
  channel_->setReadCallback(
      std::bind(&TcpConnection::handleRead, this, _1));
  channel_->setWriteCallback(
      std::bind(&TcpConnection::handleWrite, this));
  channel_->setCloseCallback(
      std::bind(&TcpConnection::handleClose, this));
  channel_->setErrorCallback(
      std::bind(&TcpConnection::handleError, this));
  LOG_DEBUG << "TcpConnection::ctor[" <<  name_ << "] at " << this
            << " fd=" << sockfd;
  socket_->setKeepAlive(true);
}

调用用户的连接回调函数

void TcpConnection::connectEstablished()
{
  loop_->assertInLoopThread();
  assert(state_ == kConnecting);
  setState(kConnected);
  //shared_from_this()是临时对象,创建时引用计数加一,销毁时减一
  channel_->tie(shared_from_this());//TcpConnection继承自enable_shared_from_this,返回这个对象的shared_ptr对象
  channel_->enableReading();

  connectionCallback_(shared_from_this());//用户回调函数
}

关闭连接

关闭连接时序图,其中的“X”表示TcpConnection通常在此析构
image
muduo中的关闭连接是被动关闭。即对方先关闭,本地read返回0,触发关闭逻辑。
为什么不能再TcpServer中直接erase()析构呢?
因为如果此时TcpConnection析构了,其中的通道Channel也就析构了,而EventLoop正在调用handleEvent(),会导致core dump。TcpConnection生命期应长于handleEvent()。
当连接到来,创建TcpConnection对象时,使用shared_ptr管理,引用计数为1;
在Channel中维护一个weak_ptr,将shared_ptr对象赋值给弱指针,引用计数仍为1;
当连接关闭,handleEvent函数中,将这个弱引用提升得到一个shared_ptr对象,引用计数变为2;
erase将指针移除,引用计数减一,TcpConnection对象不会被销毁。
调用完connCb()后,引用计数变为0;

//Channel.cc
void Channel::handleEvent(Timestamp receiveTime)
{
  std::shared_ptr<void> guard;
  if (tied_)
  {
    guard = tie_.lock(); //弱指针提升,引用计数加一
    if (guard)
    {
      handleEventWithGuard(receiveTime);
	  //调用完,引用计数为2
	  //handleEvent返回后,局部对象guard销毁,又变回1
    }
  }
  else
  {
    handleEventWithGuard(receiveTime);
  }
}

void TcpConnection::handleRead(Timestamp receiveTime)
{
  loop_->assertInLoopThread();
  int savedErrno = 0;
  ssize_t n = inputBuffer_.readFd(channel_->fd(), &savedErrno);
  if (n > 0)
  {
    messageCallback_(shared_from_this(), &inputBuffer_, receiveTime);
  }
  else if (n == 0)//返回0,连接断开
  {
    handleClose();  //关闭连接
  }
  else
  {
    errno = savedErrno;
    LOG_SYSERR << "TcpConnection::handleRead";
    handleError();
  }
}

void TcpConnection::handleClose()
{
  loop_->assertInLoopThread();
  LOG_TRACE << "fd = " << channel_->fd() << " state = " << stateToString();
  assert(state_ == kConnected || state_ == kDisconnecting);
  // we don't close fd, leave it to dtor, so we can find leaks easily.
  setState(kDisconnected);
  channel_->disableAll();
	//如果是TcpConnectionPtr guardThis(this),相当于(new TcpConnection),得到的shared_ptr引用计数为1;
	//必须是拷贝构造,引用次数才加一
  TcpConnectionPtr guardThis(shared_from_this());//返回自身对象的shared_ptr,引用计数加一,为3
  connectionCallback_(guardThis);//用户回调函数,可以不需要这一行
  // must be the last line
  closeCallback_(guardThis);  //由TcpServer/Client 注册,通知其移除连接指针
}

TcpServer/Client移除指针

void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
  // FIXME: unsafe
  loop_->runInLoop(std::bind(&TcpServer::removeConnectionInLoop, this, conn));
}

void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn)
{
  loop_->assertInLoopThread();
  LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_
           << "] - connection " << conn->name();
  size_t n = connections_.erase(conn->name());//移除,引用计数变2
  (void)n;
  assert(n == 1);
  EventLoop* ioLoop = conn->getLoop();
  ioLoop->queueInLoop(
      std::bind(&TcpConnection::connectDestroyed, conn));//引用计数加一,为3
}

TcpConnection再收尾
connectDestroyed是TcpConnection析构前最后调用的一个成员函数,通知用户连接断开。

//该函数调用完后,引用计数减为0
void TcpConnection::connectDestroyed()
{
  loop_->assertInLoopThread();
  if (state_ == kConnected)
  {
    setState(kDisconnected);
    channel_->disableAll();

    connectionCallback_(shared_from_this());
  }
  channel_->remove();//通知Poller取消对该通道的监听
}
posted @ 2021-05-24 21:11  零十  阅读(145)  评论(0编辑  收藏  举报