muduo学习之chat(示例源码解析)----server.cc

本文是chat示例源码解析的服务端程序,以注释代讲解

#include "examples/asio/chat/codec.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"

#include 
#include 
#include 

using namespace muduo;
using namespace muduo::net;

class ChatServer : noncopyable
{
 public:
  ChatServer(EventLoop* loop,
             const InetAddress& listenAddr)
  : server_(loop, listenAddr, "ChatServer"),
    codec_(std::bind(&ChatServer::onStringMessage, this, _1, _2, _3))
  {
    server_.setConnectionCallback(
        std::bind(&ChatServer::onConnection, this, _1));//绑定连接之后的回调函数
    server_.setMessageCallback(
        std::bind(&LengthHeaderCodec::onMessage, &codec_, _1, _2, _3));//绑定收到消息之后的回调函数
  }

  void start()
  {
    server_.start();//开启sever服务
  }

 private:
  void onConnection(const TcpConnectionPtr& conn)
  {
    LOG_INFO << conn->localAddress().toIpPort() << " -> "
             << conn->peerAddress().toIpPort() << " is "
             << (conn->connected() ? "UP" : "DOWN");

    if (conn->connected())
    {
      connections_.insert(conn);//收到连接之后保存到集合里
    }
    else
    {
      connections_.erase(conn);//断开连接之后把该连接从集合删除
    }
  }

  void onStringMessage(const TcpConnectionPtr&,
                       const string& message,
                       Timestamp)
  {
    for (ConnectionList::iterator it = connections_.begin();
        it != connections_.end();
        ++it)
    {
      codec_.send(get_pointer(*it), message);//收到消息之后一个一个发给客户端
    }
  }

  typedef std::set ConnectionList;
  TcpServer server_;
  LengthHeaderCodec codec_;
  ConnectionList connections_;
};

int main(int argc, char* argv[])
{
  LOG_INFO << "pid = " << getpid();
  if (argc > 1)
  {
    EventLoop loop;
    uint16_t port = static_cast(atoi(argv[1]));
    InetAddress serverAddr(port);//绑定服务器的端口
    ChatServer server(&loop, serverAddr);//绑定服务器相关参数
    server.start();//开启服务器
    loop.loop();
  }
  else
  {
    printf("Usage: %s port\n", argv[0]);
  }
}

 

你可能感兴趣的:(Linux)