1 #include "TcpServer.h" 2 #include "EventLoop.h" 3 #include "InetAddress.h" 4 #include <stdio.h> 5 6 void onConnection(const muduo::TcpConnectionPtr& conn) 7 { 8 if (conn->connected()) 9 { 10 printf("onConnection(): new connection [%s] from %s\n", 11 conn->name().c_str(), 12 conn->peerAddress().toHostPort().c_str()); 13 } 14 else 15 { 16 printf("onConnection(): connection [%s] is down\n", 17 conn->name().c_str()); 18 } 19 } 20 21 void onMessage(const muduo::TcpConnectionPtr& conn, 22! muduo::Buffer* buf, 23! muduo::Timestamp receiveTime) 24 { 25+ printf("onMessage(): received %zd bytes from connection [%s] at %s\n", 26+ buf->readableBytes(), 27+ conn->name().c_str(), 28+ receiveTime.toFormattedString().c_str()); 29+ 30+ printf("onMessage(): [%s]\n", buf->retrieveAsString().c_str()); 31 } 32 33 int main() 34 { 35 printf("main(): pid = %d\n", getpid()); 36 37 muduo::InetAddress listenAddr(9981); 38 muduo::EventLoop loop; 39 40 muduo::TcpServer server(&loop, listenAddr); 41 server.setConnectionCallback(onConnection); 42 server.setMessageCallback(onMessage); 43 server.start(); 44 45 loop.loop(); 46 } 47