test11.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 Chenstd::string message;
7e254a845SShuo Chen
8e254a845SShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn)
9e254a845SShuo Chen{
10e254a845SShuo Chen  if (conn->connected())
11e254a845SShuo Chen  {
12e254a845SShuo Chen    printf("onConnection(): new connection [%s] from %s\n",
13e254a845SShuo Chen           conn->name().c_str(),
14e254a845SShuo Chen           conn->peerAddress().toHostPort().c_str());
15e254a845SShuo Chen    conn->send(message);
16e254a845SShuo Chen  }
17e254a845SShuo Chen  else
18e254a845SShuo Chen  {
19e254a845SShuo Chen    printf("onConnection(): connection [%s] is down\n",
20e254a845SShuo Chen           conn->name().c_str());
21e254a845SShuo Chen  }
22e254a845SShuo Chen}
23e254a845SShuo Chen
24e254a845SShuo Chenvoid onWriteComplete(const muduo::TcpConnectionPtr& conn)
25e254a845SShuo Chen{
26e254a845SShuo Chen  conn->send(message);
27e254a845SShuo Chen}
28e254a845SShuo Chen
29e254a845SShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn,
30e254a845SShuo Chen               muduo::Buffer* buf,
31e254a845SShuo Chen               muduo::Timestamp receiveTime)
32e254a845SShuo Chen{
33e254a845SShuo Chen  printf("onMessage(): received %3zd bytes from connection [%s] at %s\n",
34e254a845SShuo Chen         buf->readableBytes(),
35e254a845SShuo Chen         conn->name().c_str(),
36e254a845SShuo Chen         receiveTime.toFormattedString().c_str());
37e254a845SShuo Chen
38e254a845SShuo Chen  buf->retrieveAll();
39e254a845SShuo Chen}
40e254a845SShuo Chen
41e254a845SShuo Chenint main()
42e254a845SShuo Chen{
43e254a845SShuo Chen  printf("main(): pid = %d\n", getpid());
44e254a845SShuo Chen
45e254a845SShuo Chen  std::string line;
46e254a845SShuo Chen  for (int i = 33; i < 127; ++i)
47e254a845SShuo Chen  {
48e254a845SShuo Chen    line.push_back(char(i));
49e254a845SShuo Chen  }
50e254a845SShuo Chen  line += line;
51e254a845SShuo Chen
52e254a845SShuo Chen  for (size_t i = 0; i < 127-33; ++i)
53e254a845SShuo Chen  {
54e254a845SShuo Chen    message += line.substr(i, 72) + '\n';
55e254a845SShuo Chen  }
56e254a845SShuo Chen
57e254a845SShuo Chen  muduo::InetAddress listenAddr(9981);
58e254a845SShuo Chen  muduo::EventLoop loop;
59e254a845SShuo Chen
60e254a845SShuo Chen  muduo::TcpServer server(&loop, listenAddr);
61e254a845SShuo Chen  server.setConnectionCallback(onConnection);
62e254a845SShuo Chen  server.setMessageCallback(onMessage);
63e254a845SShuo Chen  server.setWriteCompleteCallback(onWriteComplete);
64e254a845SShuo Chen  server.start();
65e254a845SShuo Chen
66e254a845SShuo Chen  loop.loop();
67e254a845SShuo Chen}
68