1129fe122SShuo Chen#include "TcpServer.h"
2129fe122SShuo Chen#include "EventLoop.h"
3129fe122SShuo Chen#include "InetAddress.h"
4129fe122SShuo Chen#include <stdio.h>
5129fe122SShuo Chen
6129fe122SShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn)
7129fe122SShuo Chen{
8129fe122SShuo Chen  if (conn->connected())
9129fe122SShuo Chen  {
10129fe122SShuo Chen    printf("onConnection(): new connection [%s] from %s\n",
11129fe122SShuo Chen           conn->name().c_str(),
12129fe122SShuo Chen           conn->peerAddress().toHostPort().c_str());
13129fe122SShuo Chen  }
14129fe122SShuo Chen  else
15129fe122SShuo Chen  {
16129fe122SShuo Chen    printf("onConnection(): connection [%s] is down\n",
17129fe122SShuo Chen           conn->name().c_str());
18129fe122SShuo Chen  }
19129fe122SShuo Chen}
20129fe122SShuo Chen
21129fe122SShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn,
22129fe122SShuo Chen               muduo::Buffer* buf,
23129fe122SShuo Chen               muduo::Timestamp receiveTime)
24129fe122SShuo Chen{
250ce27c5bSShuo Chen  printf("onMessage(): received %zd bytes from connection [%s] at %s\n",
26129fe122SShuo Chen         buf->readableBytes(),
27129fe122SShuo Chen         conn->name().c_str(),
28129fe122SShuo Chen         receiveTime.toFormattedString().c_str());
29129fe122SShuo Chen
30129fe122SShuo Chen  conn->send(buf->retrieveAsString());
31129fe122SShuo Chen}
32129fe122SShuo Chen
33129fe122SShuo Chenint main()
34129fe122SShuo Chen{
35129fe122SShuo Chen  printf("main(): pid = %d\n", getpid());
36129fe122SShuo Chen
37129fe122SShuo Chen  muduo::InetAddress listenAddr(9981);
38129fe122SShuo Chen  muduo::EventLoop loop;
39129fe122SShuo Chen
40129fe122SShuo Chen  muduo::TcpServer server(&loop, listenAddr);
41129fe122SShuo Chen  server.setConnectionCallback(onConnection);
42129fe122SShuo Chen  server.setMessageCallback(onMessage);
43129fe122SShuo Chen  server.start();
44129fe122SShuo Chen
45129fe122SShuo Chen  loop.loop();
46129fe122SShuo Chen}
47