1#include "TcpServer.h" 2#include "EventLoop.h" 3#include "InetAddress.h" 4#include <stdio.h> 5 6std::string message; 7 8void onConnection(const muduo::TcpConnectionPtr& conn) 9{ 10 if (conn->connected()) 11 { 12 printf("onConnection(): new connection [%s] from %s\n", 13 conn->name().c_str(), 14 conn->peerAddress().toHostPort().c_str()); 15 conn->send(message); 16 } 17 else 18 { 19 printf("onConnection(): connection [%s] is down\n", 20 conn->name().c_str()); 21 } 22} 23 24void onWriteComplete(const muduo::TcpConnectionPtr& conn) 25{ 26 conn->send(message); 27} 28 29void onMessage(const muduo::TcpConnectionPtr& conn, 30 muduo::Buffer* buf, 31 muduo::Timestamp receiveTime) 32{ 33 printf("onMessage(): received %zd bytes from connection [%s] at %s\n", 34 buf->readableBytes(), 35 conn->name().c_str(), 36 receiveTime.toFormattedString().c_str()); 37 38 buf->retrieveAll(); 39} 40 41int main() 42{ 43 printf("main(): pid = %d\n", getpid()); 44 45 std::string line; 46 for (int i = 33; i < 127; ++i) 47 { 48 line.push_back(char(i)); 49 } 50 line += line; 51 52 for (size_t i = 0; i < 127-33; ++i) 53 { 54 message += line.substr(i, 72) + '\n'; 55 } 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.setWriteCompleteCallback(onWriteComplete); 64 server.start(); 65 66 loop.loop(); 67} 68