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