muduo源码分析之TcpServer

相关文件

muduo/net/TcpServer.h
muduo/net/TcpServer.cc

作用

使用

使用命令 nc 127.0.0.1 8888 作为客户端连接上开启的服务器

#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>

#include <stdio.h>

using namespace muduo;
using namespace muduo::net;

void onConnection(const TcpConnectionPtr& conn)
{
  if (conn->connected())
  {
    printf("onConnection(): new connection [%s] from %s\n",
           conn->name().c_str(),
           conn->peerAddress().toIpPort().c_str());
  }
  else
  {
    printf("onConnection(): connection [%s] is down\n",
           conn->name().c_str());
  }
}


void onMessage(const TcpConnectionPtr& conn,
               Buffer* buf,
               Timestamp time)
{ 
  string msg(buf->retrieveAllAsString());
  printf("onMessage(): received %zd bytes from connection [%s]\n",
         msg.size(), conn->name().c_str());
}

int main()
{
  printf("main(): pid = %d\n", getpid());

  InetAddress listenAddr(8888);//端口号
  EventLoop loop;

  TcpServer server(&loop, listenAddr, "TestServer");
  server.setConnectionCallback(onConnection);
  server.setMessageCallback(onMessage);
  server.start();

  loop.loop();
}


上一篇:使用muduo网络库编译出现error: reference to ‘_1’ is ambiguous


下一篇:C语言学习笔记---嵌套结构体