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