Welcome

首页 / 软件开发 / C++ / muduo 的 shutdown()没有直接关闭 TCP连接的原因

muduo 的 shutdown()没有直接关闭 TCP连接的原因2014-04-03 陈硕 今天收到一位网友来信:

在 simple 中的 daytime 示例中,服务端主动关闭时调用的是如 下函数序列,这不是只是关闭了连接上的写操作吗,怎么是关闭了整个连接?

1: void DaytimeServer::onConnection(const muduo::net::TcpConnectionPtr& conn)

2: {

3:   if (conn->connected())

4:   {

5:     conn->send(Timestamp::now().toFormattedString() + " ");

6:     conn->shutdown();

7:   }

8: }

9:

10: void TcpConnection::shutdown()

11: {

12:   if (state_ == kConnected)

13:   {

14:     setState(kDisconnecting);

15:     loop_->runInLoop(boost::bind(&TcpConnection::shutdownInLoop, this));

16:   }

17: }

18:

19: void TcpConnection::shutdownInLoop ()

20: {

21:   loop_->assertInLoopThread();

22:   if (! channel_->isWriting())

23:   {

24:     // we are not writing

25:     socket_->shutdownWrite();

26:   }

27: }

28:

29: void Socket::shutdownWrite()

30: {

31:   sockets::shutdownWrite(sockfd_);

32: }

33:

34: void sockets::shutdownWrite (int sockfd)

35: {

36:   if (::shutdown(sockfd, SHUT_WR) < 0)

37:   {

38:     LOG_SYSERR << "sockets::shutdownWrite";

39:   }

40: }