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