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