-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
85 lines (71 loc) · 1.79 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "TcpServer.h"
//#include <muduo/base/Logging.h>
#include "EventLoop.h"
#include "InetAddress.h"
#include "Logging.h"
#include <boost/bind.hpp>
#include "CurrentThread.h"
#include <utility>
#include <stdio.h>
#include <unistd.h>
int numThreads = 0;
class EchoServer
{
public:
EchoServer(EventLoop* loop, const InetAddress& listenAddr)
: loop_(loop),
server_(loop, listenAddr, "EchoServer")
{
server_.setConnectionCallback(
boost::bind(&EchoServer::onConnection, this, _1));
server_.setMessageCallback(
boost::bind(&EchoServer::onMessage, this, _1, _2));
server_.setThreadNum(numThreads);
}
void start()
{
server_.start();
}
// void stop();
private:
void onConnection(const TcpConnectionPtr& conn)
{
/*LOG_TRACE << conn->peerAddress().toIpPort() << " -> "
<< conn->localAddress().toIpPort() << " is "
<< (conn->connected() ? "UP" : "DOWN");*/
LOG_INFO << conn->getTcpInfoString();
conn->send("hello\n");
}
void onMessage(const TcpConnectionPtr& conn, Buffer* buf)
{
string msg(buf->retrieveAllAsString());
// LOG_TRACE << conn->name() << " recv " << msg.size() << " bytes at " << time.toString();
if (msg == "exit\n")
{
conn->send("bye\n");
conn->shutdown();
}
if (msg == "quit\n")
{
loop_->quit();
}
conn->send(msg);
}
EventLoop* loop_;
TcpServer server_;
};
int main(int argc, char* argv[])
{
LOG_INFO << "pid = " << getpid() << ", tid = " << muduo::CurrentThread::tid();
LOG_INFO << "sizeof TcpConnection = " << sizeof(TcpConnection);
if (argc > 1)
{
numThreads = atoi(argv[1]);
}
bool ipv6 = argc > 2;
EventLoop loop;
InetAddress listenAddr(2000, false, ipv6);
EchoServer server(&loop, listenAddr);
server.start();
loop.loop();
}