1e254a845SShuo Chen#include "TcpServer.h" 2e254a845SShuo Chen#include "EventLoop.h" 3e254a845SShuo Chen#include "InetAddress.h" 4e254a845SShuo Chen#include <stdio.h> 5e254a845SShuo Chen 6e254a845SShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn) 7e254a845SShuo Chen{ 8e254a845SShuo Chen if (conn->connected()) 9e254a845SShuo Chen { 100ce27c5bSShuo Chen printf("onConnection(): tid=%d new connection [%s] from %s\n", 110ce27c5bSShuo Chen muduo::CurrentThread::tid(), 12e254a845SShuo Chen conn->name().c_str(), 13e254a845SShuo Chen conn->peerAddress().toHostPort().c_str()); 14e254a845SShuo Chen } 15e254a845SShuo Chen else 16e254a845SShuo Chen { 170ce27c5bSShuo Chen printf("onConnection(): tid=%d connection [%s] is down\n", 180ce27c5bSShuo Chen muduo::CurrentThread::tid(), 19e254a845SShuo Chen conn->name().c_str()); 20e254a845SShuo Chen } 21e254a845SShuo Chen} 22e254a845SShuo Chen 23e254a845SShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn, 24e254a845SShuo Chen muduo::Buffer* buf, 25e254a845SShuo Chen muduo::Timestamp receiveTime) 26e254a845SShuo Chen{ 270ce27c5bSShuo Chen printf("onMessage(): tid=%d received %zd bytes from connection [%s] at %s\n", 280ce27c5bSShuo Chen muduo::CurrentThread::tid(), 29e254a845SShuo Chen buf->readableBytes(), 30e254a845SShuo Chen conn->name().c_str(), 31e254a845SShuo Chen receiveTime.toFormattedString().c_str()); 32e254a845SShuo Chen 33e254a845SShuo Chen printf("onMessage(): [%s]\n", buf->retrieveAsString().c_str()); 34e254a845SShuo Chen} 35e254a845SShuo Chen 360ce27c5bSShuo Chenint main(int argc, char* argv[]) 37e254a845SShuo Chen{ 38e254a845SShuo Chen printf("main(): pid = %d\n", getpid()); 39e254a845SShuo Chen 40e254a845SShuo Chen muduo::InetAddress listenAddr(9981); 41e254a845SShuo Chen muduo::EventLoop loop; 42e254a845SShuo Chen 43e254a845SShuo Chen muduo::TcpServer server(&loop, listenAddr); 44e254a845SShuo Chen server.setConnectionCallback(onConnection); 45e254a845SShuo Chen server.setMessageCallback(onMessage); 460ce27c5bSShuo Chen if (argc > 1) { 470ce27c5bSShuo Chen server.setThreadNum(atoi(argv[1])); 480ce27c5bSShuo Chen } 49e254a845SShuo Chen server.start(); 50e254a845SShuo Chen 51e254a845SShuo Chen loop.loop(); 52e254a845SShuo Chen} 53