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