1#include "EventLoop.h"
2#include "InetAddress.h"
3#include "TcpClient.h"
4
5#include "logging/Logging.h"
6
7#include <boost/bind.hpp>
8
9#include <utility>
10
11#include <stdio.h>
12#include <unistd.h>
13
14std::string message = "Hello\n";
15
16void onConnection(const muduo::TcpConnectionPtr& conn)
17{
18  if (conn->connected())
19  {
20    printf("onConnection(): new connection [%s] from %s\n",
21           conn->name().c_str(),
22           conn->peerAddress().toHostPort().c_str());
23    conn->send(message);
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  printf("onMessage(): [%s]\n", buf->retrieveAsString().c_str());
42}
43
44int main()
45{
46  muduo::EventLoop loop;
47  muduo::InetAddress serverAddr("localhost", 9981);
48  muduo::TcpClient client(&loop, serverAddr);
49
50  client.setConnectionCallback(onConnection);
51  client.setMessageCallback(onMessage);
52  client.enableRetry();
53  client.connect();
54  loop.loop();
55}
56
57