test8.cc revision e254a845
1e254a845SShuo Chen#include "TcpServer.h"
2e254a845SShuo Chen#include "EventLoop.h"
3e254a845SShuo Chen#include "InetAddress.h"
4e254a845SShuo Chen#include <stdio.h>
5e254a845SShuo Chen
6e254a845SShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn)
7e254a845SShuo Chen{
8e254a845SShuo Chen  if (conn->connected())
9e254a845SShuo Chen  {
10e254a845SShuo Chen    printf("onConnection(): new connection [%s] from %s\n",
11e254a845SShuo Chen           conn->name().c_str(),
12e254a845SShuo Chen           conn->peerAddress().toHostPort().c_str());
13e254a845SShuo Chen  }
14e254a845SShuo Chen  else
15e254a845SShuo Chen  {
16e254a845SShuo Chen    printf("onConnection(): connection [%s] is down\n",
17e254a845SShuo Chen           conn->name().c_str());
18e254a845SShuo Chen  }
19e254a845SShuo Chen}
20e254a845SShuo Chen
21e254a845SShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn,
22e254a845SShuo Chen               muduo::Buffer* buf,
23e254a845SShuo Chen               muduo::Timestamp receiveTime)
24e254a845SShuo Chen{
25e254a845SShuo Chen  printf("onMessage(): received %3zd bytes from connection [%s] at %s\n",
26e254a845SShuo Chen         buf->readableBytes(),
27e254a845SShuo Chen         conn->name().c_str(),
28e254a845SShuo Chen         receiveTime.toFormattedString().c_str());
29e254a845SShuo Chen
30e254a845SShuo Chen  printf("onMessage(): [%s]\n", buf->retrieveAsString().c_str());
31e254a845SShuo Chen}
32e254a845SShuo Chen
33e254a845SShuo Chenint main()
34e254a845SShuo Chen{
35e254a845SShuo Chen  printf("main(): pid = %d\n", getpid());
36e254a845SShuo Chen
37e254a845SShuo Chen  muduo::InetAddress listenAddr(9981);
38e254a845SShuo Chen  muduo::EventLoop loop;
39e254a845SShuo Chen
40e254a845SShuo Chen  muduo::TcpServer server(&loop, listenAddr);
41e254a845SShuo Chen  server.setConnectionCallback(onConnection);
42e254a845SShuo Chen  server.setMessageCallback(onMessage);
43e254a845SShuo Chen  server.start();
44e254a845SShuo Chen
45e254a845SShuo Chen  loop.loop();
46e254a845SShuo Chen}
47