1#include "TcpServer.h" 2#include "EventLoop.h" 3#include "InetAddress.h" 4#include <stdio.h> 5 6void 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 21void onMessage(const muduo::TcpConnectionPtr& conn, 22 const char* data, 23 ssize_t len) 24{ 25 printf("onMessage(): received %zd bytes from connection [%s]\n", 26 len, conn->name().c_str()); 27} 28 29int main() 30{ 31 printf("main(): pid = %d\n", getpid()); 32 33 muduo::InetAddress listenAddr(9981); 34 muduo::EventLoop loop; 35 36 muduo::TcpServer server(&loop, listenAddr); 37 server.setConnectionCallback(onConnection); 38 server.setMessageCallback(onMessage); 39 server.start(); 40 41 loop.loop(); 42} 43