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