1 #include "TcpServer.h" 2 #include "EventLoop.h" 3 #include "InetAddress.h" 4 #include <stdio.h> 5 6 std::string message; 7 8 void onConnection(const muduo::TcpConnectionPtr& conn) 9 { 10 if (conn->connected()) 11 { 12! printf("onConnection(): tid=%d new connection [%s] from %s\n", 13+ muduo::CurrentThread::tid(), 14 conn->name().c_str(), 15 conn->peerAddress().toHostPort().c_str()); 16 conn->send(message); 17 } 18 else 19 { 20! printf("onConnection(): tid=%d connection [%s] is down\n", 21+ muduo::CurrentThread::tid(), 22 conn->name().c_str()); 23 } 24 } 25 26 void onWriteComplete(const muduo::TcpConnectionPtr& conn) 27 { 28 conn->send(message); 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 std::string line; 49 for (int i = 33; i < 127; ++i) 50 { 51 line.push_back(char(i)); 52 } 53 line += line; 54 55 for (size_t i = 0; i < 127-33; ++i) 56 { 57 message += line.substr(i, 72) + '\n'; 58 } 59 60 muduo::InetAddress listenAddr(9981); 61 muduo::EventLoop loop; 62 63 muduo::TcpServer server(&loop, listenAddr); 64 server.setConnectionCallback(onConnection); 65 server.setMessageCallback(onMessage); 66 server.setWriteCompleteCallback(onWriteComplete); 67+ if (argc > 1) { 68+ server.setThreadNum(atoi(argv[1])); 69+ } 70 server.start(); 71 72 loop.loop(); 73 } 74