140161064SShuo Chen #include "TcpServer.h" 240161064SShuo Chen #include "EventLoop.h" 340161064SShuo Chen #include "InetAddress.h" 440161064SShuo Chen #include <stdio.h> 540161064SShuo Chen 640161064SShuo Chen std::string message; 740161064SShuo Chen 840161064SShuo Chen void onConnection(const muduo::TcpConnectionPtr& conn) 940161064SShuo Chen { 1040161064SShuo Chen if (conn->connected()) 1140161064SShuo Chen { 1240161064SShuo Chen! printf("onConnection(): tid=%d new connection [%s] from %s\n", 1340161064SShuo Chen+ muduo::CurrentThread::tid(), 1440161064SShuo Chen conn->name().c_str(), 1540161064SShuo Chen conn->peerAddress().toHostPort().c_str()); 1640161064SShuo Chen conn->send(message); 1740161064SShuo Chen } 1840161064SShuo Chen else 1940161064SShuo Chen { 2040161064SShuo Chen! printf("onConnection(): tid=%d connection [%s] is down\n", 2140161064SShuo Chen+ muduo::CurrentThread::tid(), 2240161064SShuo Chen conn->name().c_str()); 2340161064SShuo Chen } 2440161064SShuo Chen } 2540161064SShuo Chen 2640161064SShuo Chen void onWriteComplete(const muduo::TcpConnectionPtr& conn) 2740161064SShuo Chen { 2840161064SShuo Chen conn->send(message); 2940161064SShuo Chen } 3040161064SShuo Chen 3140161064SShuo Chen void onMessage(const muduo::TcpConnectionPtr& conn, 3240161064SShuo Chen muduo::Buffer* buf, 3340161064SShuo Chen muduo::Timestamp receiveTime) 3440161064SShuo Chen { 3540161064SShuo Chen! printf("onMessage(): tid=%d received %zd bytes from connection [%s] at %s\n", 3640161064SShuo Chen+ muduo::CurrentThread::tid(), 3740161064SShuo Chen buf->readableBytes(), 3840161064SShuo Chen conn->name().c_str(), 3940161064SShuo Chen receiveTime.toFormattedString().c_str()); 4040161064SShuo Chen 4140161064SShuo Chen buf->retrieveAll(); 4240161064SShuo Chen } 4340161064SShuo Chen 4440161064SShuo Chen!int main(int argc, char* argv[]) 4540161064SShuo Chen { 4640161064SShuo Chen printf("main(): pid = %d\n", getpid()); 4740161064SShuo Chen 4840161064SShuo Chen std::string line; 4940161064SShuo Chen for (int i = 33; i < 127; ++i) 5040161064SShuo Chen { 5140161064SShuo Chen line.push_back(char(i)); 5240161064SShuo Chen } 5340161064SShuo Chen line += line; 5440161064SShuo Chen 5540161064SShuo Chen for (size_t i = 0; i < 127-33; ++i) 5640161064SShuo Chen { 5740161064SShuo Chen message += line.substr(i, 72) + '\n'; 5840161064SShuo Chen } 5940161064SShuo Chen 6040161064SShuo Chen muduo::InetAddress listenAddr(9981); 6140161064SShuo Chen muduo::EventLoop loop; 6240161064SShuo Chen 6340161064SShuo Chen muduo::TcpServer server(&loop, listenAddr); 6440161064SShuo Chen server.setConnectionCallback(onConnection); 6540161064SShuo Chen server.setMessageCallback(onMessage); 6640161064SShuo Chen server.setWriteCompleteCallback(onWriteComplete); 6740161064SShuo Chen+ if (argc > 1) { 6840161064SShuo Chen+ server.setThreadNum(atoi(argv[1])); 6940161064SShuo Chen+ } 7040161064SShuo Chen server.start(); 7140161064SShuo Chen 7240161064SShuo Chen loop.loop(); 7340161064SShuo Chen } 74