1#include "TcpServer.h"
2#include "EventLoop.h"
3#include "InetAddress.h"
4#include <stdio.h>
5
6std::string message1;
7std::string message2;
8int sleepSeconds = 0;
9
10void onConnection(const muduo::TcpConnectionPtr& conn)
11{
12  if (conn->connected())
13  {
14    printf("onConnection(): new connection [%s] from %s\n",
15           conn->name().c_str(),
16           conn->peerAddress().toHostPort().c_str());
17    if (sleepSeconds > 0)
18    {
19      ::sleep(sleepSeconds);
20    }
21    conn->send(message1);
22    conn->send(message2);
23    conn->shutdown();
24  }
25  else
26  {
27    printf("onConnection(): connection [%s] is down\n",
28           conn->name().c_str());
29  }
30}
31
32void onMessage(const muduo::TcpConnectionPtr& conn,
33               muduo::Buffer* buf,
34               muduo::Timestamp receiveTime)
35{
36  printf("onMessage(): received %zd bytes from connection [%s] at %s\n",
37         buf->readableBytes(),
38         conn->name().c_str(),
39         receiveTime.toFormattedString().c_str());
40
41  buf->retrieveAll();
42}
43
44int main(int argc, char* argv[])
45{
46  printf("main(): pid = %d\n", getpid());
47
48  int len1 = 100;
49  int len2 = 200;
50
51  if (argc > 2)
52  {
53    len1 = atoi(argv[1]);
54    len2 = atoi(argv[2]);
55  }
56  if (argc > 3)
57  {
58    sleepSeconds = atoi(argv[3]);
59  }
60
61  message1.resize(len1);
62  message2.resize(len2);
63  std::fill(message1.begin(), message1.end(), 'A');
64  std::fill(message2.begin(), message2.end(), 'B');
65
66  muduo::InetAddress listenAddr(9981);
67  muduo::EventLoop loop;
68
69  muduo::TcpServer server(&loop, listenAddr);
70  server.setConnectionCallback(onConnection);
71  server.setMessageCallback(onMessage);
72  server.start();
73
74  loop.loop();
75}
76