1 #include "TcpServer.h" 2 #include "EventLoop.h" 3 #include "InetAddress.h" 4 #include <stdio.h> 5 6 std::string message1; 7 std::string message2; 8 9 void onConnection(const muduo::TcpConnectionPtr& conn) 10 { 11 if (conn->connected()) 12 { 13! printf("onConnection(): tid=%d new connection [%s] from %s\n", 14+ muduo::CurrentThread::tid(), 15 conn->name().c_str(), 16 conn->peerAddress().toHostPort().c_str()); 17+ if (!message1.empty()) 18 conn->send(message1); 19+ if (!message2.empty()) 20 conn->send(message2); 21 conn->shutdown(); 22 } 23 else 24 { 25! printf("onConnection(): tid=%d connection [%s] is down\n", 26+ muduo::CurrentThread::tid(), 27 conn->name().c_str()); 28 } 29 } 30 31 void onMessage(const muduo::TcpConnectionPtr& conn, 32 muduo::Buffer* buf, 33 muduo::Timestamp receiveTime) 34 { 35! printf("onMessage(): tid=%d received %zd bytes from connection [%s] at %s\n", 36+ muduo::CurrentThread::tid(), 37 buf->readableBytes(), 38 conn->name().c_str(), 39 receiveTime.toFormattedString().c_str()); 40 41 buf->retrieveAll(); 42 } 43 44 int main(int argc, char* argv[]) 45 { 46 printf("main(): pid = %d\n", getpid()); 47 48 int len1 = 100; 49 int len2 = 200; 50 51 if (argc > 2) 52 { 53 len1 = atoi(argv[1]); 54 len2 = atoi(argv[2]); 55 } 56 57 message1.resize(len1); 58 message2.resize(len2); 59 std::fill(message1.begin(), message1.end(), 'A'); 60 std::fill(message2.begin(), message2.end(), 'B'); 61 62 muduo::InetAddress listenAddr(9981); 63 muduo::EventLoop loop; 64 65 muduo::TcpServer server(&loop, listenAddr); 66 server.setConnectionCallback(onConnection); 67 server.setMessageCallback(onMessage); 68+ if (argc > 3) { 69+ server.setThreadNum(atoi(argv[3])); 70+ } 71 server.start(); 72 73 loop.loop(); 74 } 75