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