140161064SShuo Chen #include "TcpServer.h" 240161064SShuo Chen #include "EventLoop.h" 340161064SShuo Chen #include "InetAddress.h" 440161064SShuo Chen #include <stdio.h> 540161064SShuo Chen 640161064SShuo Chen void onConnection(const muduo::TcpConnectionPtr& conn) 740161064SShuo Chen { 840161064SShuo Chen if (conn->connected()) 940161064SShuo Chen { 1040161064SShuo Chen! printf("onConnection(): tid=%d new connection [%s] from %s\n", 1140161064SShuo Chen+ muduo::CurrentThread::tid(), 1240161064SShuo Chen conn->name().c_str(), 1340161064SShuo Chen conn->peerAddress().toHostPort().c_str()); 1440161064SShuo Chen } 1540161064SShuo Chen else 1640161064SShuo Chen { 1740161064SShuo Chen! printf("onConnection(): tid=%d connection [%s] is down\n", 1840161064SShuo Chen+ muduo::CurrentThread::tid(), 1940161064SShuo Chen conn->name().c_str()); 2040161064SShuo Chen } 2140161064SShuo Chen } 2240161064SShuo Chen 2340161064SShuo Chen void onMessage(const muduo::TcpConnectionPtr& conn, 2440161064SShuo Chen muduo::Buffer* buf, 2540161064SShuo Chen muduo::Timestamp receiveTime) 2640161064SShuo Chen { 2740161064SShuo Chen! printf("onMessage(): tid=%d received %zd bytes from connection [%s] at %s\n", 2840161064SShuo Chen+ muduo::CurrentThread::tid(), 2940161064SShuo Chen buf->readableBytes(), 3040161064SShuo Chen conn->name().c_str(), 3140161064SShuo Chen receiveTime.toFormattedString().c_str()); 3240161064SShuo Chen 3340161064SShuo Chen conn->send(buf->retrieveAsString()); 3440161064SShuo Chen } 3540161064SShuo Chen 3640161064SShuo Chen!int main(int argc, char* argv[]) 3740161064SShuo Chen { 3840161064SShuo Chen printf("main(): pid = %d\n", getpid()); 3940161064SShuo Chen 4040161064SShuo Chen muduo::InetAddress listenAddr(9981); 4140161064SShuo Chen muduo::EventLoop loop; 4240161064SShuo Chen 4340161064SShuo Chen muduo::TcpServer server(&loop, listenAddr); 4440161064SShuo Chen server.setConnectionCallback(onConnection); 4540161064SShuo Chen server.setMessageCallback(onMessage); 4640161064SShuo Chen+ if (argc > 1) { 4740161064SShuo Chen+ server.setThreadNum(atoi(argv[1])); 4840161064SShuo Chen+ } 4940161064SShuo Chen server.start(); 5040161064SShuo Chen 5140161064SShuo Chen loop.loop(); 5240161064SShuo Chen } 53