1354280cfSShuo Chen#include "TcpServer.h"
2354280cfSShuo Chen#include "EventLoop.h"
3354280cfSShuo Chen#include "InetAddress.h"
4354280cfSShuo Chen#include <stdio.h>
5354280cfSShuo Chen
6354280cfSShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn)
7354280cfSShuo Chen{
8354280cfSShuo Chen  if (conn->connected())
9354280cfSShuo Chen  {
10354280cfSShuo Chen    printf("onConnection(): tid=%d new connection [%s] from %s\n",
11354280cfSShuo Chen           muduo::CurrentThread::tid(),
12354280cfSShuo Chen           conn->name().c_str(),
13354280cfSShuo Chen           conn->peerAddress().toHostPort().c_str());
14354280cfSShuo Chen  }
15354280cfSShuo Chen  else
16354280cfSShuo Chen  {
17354280cfSShuo Chen    printf("onConnection(): tid=%d connection [%s] is down\n",
18354280cfSShuo Chen           muduo::CurrentThread::tid(),
19354280cfSShuo Chen           conn->name().c_str());
20354280cfSShuo Chen  }
21354280cfSShuo Chen}
22354280cfSShuo Chen
23354280cfSShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn,
24354280cfSShuo Chen               muduo::Buffer* buf,
25354280cfSShuo Chen               muduo::Timestamp receiveTime)
26354280cfSShuo Chen{
27354280cfSShuo Chen  printf("onMessage(): tid=%d received %zd bytes from connection [%s] at %s\n",
28354280cfSShuo Chen         muduo::CurrentThread::tid(),
29354280cfSShuo Chen         buf->readableBytes(),
30354280cfSShuo Chen         conn->name().c_str(),
31354280cfSShuo Chen         receiveTime.toFormattedString().c_str());
32354280cfSShuo Chen
33354280cfSShuo Chen  conn->send(buf->retrieveAsString());
34354280cfSShuo Chen}
35354280cfSShuo Chen
36354280cfSShuo Chenint main(int argc, char* argv[])
37354280cfSShuo Chen{
38354280cfSShuo Chen  printf("main(): pid = %d\n", getpid());
39354280cfSShuo Chen
40354280cfSShuo Chen  muduo::InetAddress listenAddr(9981);
41354280cfSShuo Chen  muduo::EventLoop loop;
42354280cfSShuo Chen
43354280cfSShuo Chen  muduo::TcpServer server(&loop, listenAddr);
44354280cfSShuo Chen  server.setConnectionCallback(onConnection);
45354280cfSShuo Chen  server.setMessageCallback(onMessage);
46354280cfSShuo Chen  if (argc > 1) {
47354280cfSShuo Chen    server.setThreadNum(atoi(argv[1]));
48354280cfSShuo Chen  }
49354280cfSShuo Chen  server.start();
50354280cfSShuo Chen
51354280cfSShuo Chen  loop.loop();
52354280cfSShuo Chen}
53