1129fe122SShuo Chen#include "TcpServer.h" 2129fe122SShuo Chen#include "EventLoop.h" 3129fe122SShuo Chen#include "InetAddress.h" 4129fe122SShuo Chen#include <stdio.h> 5129fe122SShuo Chen 6129fe122SShuo Chenstd::string message1; 7129fe122SShuo Chenstd::string message2; 8129fe122SShuo Chen 9129fe122SShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn) 10129fe122SShuo Chen{ 11129fe122SShuo Chen if (conn->connected()) 12129fe122SShuo Chen { 13129fe122SShuo Chen printf("onConnection(): new connection [%s] from %s\n", 14129fe122SShuo Chen conn->name().c_str(), 15129fe122SShuo Chen conn->peerAddress().toHostPort().c_str()); 16129fe122SShuo Chen conn->send(message1); 17129fe122SShuo Chen conn->send(message2); 18129fe122SShuo Chen conn->shutdown(); 19129fe122SShuo Chen } 20129fe122SShuo Chen else 21129fe122SShuo Chen { 22129fe122SShuo Chen printf("onConnection(): connection [%s] is down\n", 23129fe122SShuo Chen conn->name().c_str()); 24129fe122SShuo Chen } 25129fe122SShuo Chen} 26129fe122SShuo Chen 27129fe122SShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn, 28129fe122SShuo Chen muduo::Buffer* buf, 29129fe122SShuo Chen muduo::Timestamp receiveTime) 30129fe122SShuo Chen{ 310ce27c5bSShuo Chen printf("onMessage(): received %zd bytes from connection [%s] at %s\n", 32129fe122SShuo Chen buf->readableBytes(), 33129fe122SShuo Chen conn->name().c_str(), 34129fe122SShuo Chen receiveTime.toFormattedString().c_str()); 35129fe122SShuo Chen 36129fe122SShuo Chen buf->retrieveAll(); 37129fe122SShuo Chen} 38129fe122SShuo Chen 39129fe122SShuo Chenint main(int argc, char* argv[]) 40129fe122SShuo Chen{ 41129fe122SShuo Chen printf("main(): pid = %d\n", getpid()); 42129fe122SShuo Chen 43129fe122SShuo Chen int len1 = 100; 44129fe122SShuo Chen int len2 = 200; 45129fe122SShuo Chen 46129fe122SShuo Chen if (argc > 2) 47129fe122SShuo Chen { 48129fe122SShuo Chen len1 = atoi(argv[1]); 49129fe122SShuo Chen len2 = atoi(argv[2]); 50129fe122SShuo Chen } 51129fe122SShuo Chen 52129fe122SShuo Chen message1.resize(len1); 53129fe122SShuo Chen message2.resize(len2); 54129fe122SShuo Chen std::fill(message1.begin(), message1.end(), 'A'); 55129fe122SShuo Chen std::fill(message2.begin(), message2.end(), 'B'); 56129fe122SShuo Chen 57129fe122SShuo Chen muduo::InetAddress listenAddr(9981); 58129fe122SShuo Chen muduo::EventLoop loop; 59129fe122SShuo Chen 60129fe122SShuo Chen muduo::TcpServer server(&loop, listenAddr); 61129fe122SShuo Chen server.setConnectionCallback(onConnection); 62129fe122SShuo Chen server.setMessageCallback(onMessage); 63129fe122SShuo Chen server.start(); 64129fe122SShuo Chen 65129fe122SShuo Chen loop.loop(); 66129fe122SShuo Chen} 67