-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
TcpServer_test.cpp
75 lines (64 loc) · 1.91 KB
/
TcpServer_test.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
/*
* TcpServer_test.cpp
*
* @build make evpp
* @server bin/TcpServer_test 1234
* @client bin/TcpClient_test 1234
*
*/
#include <iostream>
#include "TcpServer.h"
using namespace hv;
#define TEST_TLS 0
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s port\n", argv[0]);
return -10;
}
int port = atoi(argv[1]);
hlog_set_level(LOG_LEVEL_DEBUG);
TcpServer srv;
int listenfd = srv.createsocket(port);
if (listenfd < 0) {
return -20;
}
printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
srv.onConnection = [](const SocketChannelPtr& channel) {
std::string peeraddr = channel->peeraddr();
if (channel->isConnected()) {
printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
} else {
printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
}
};
srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
// echo
printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
channel->write(buf);
};
srv.setThreadNum(4);
srv.setLoadBalance(LB_LeastConnections);
#if TEST_TLS
hssl_ctx_opt_t ssl_opt;
memset(&ssl_opt, 0, sizeof(hssl_ctx_opt_t));
ssl_opt.crt_file = "cert/server.crt";
ssl_opt.key_file = "cert/server.key";
ssl_opt.verify_peer = 0;
srv.withTLS(&ssl_opt);
#endif
srv.start();
std::string str;
while (std::getline(std::cin, str)) {
if (str == "close") {
srv.closesocket();
} else if (str == "start") {
srv.start();
} else if (str == "stop") {
srv.stop();
break;
} else {
srv.broadcast(str.data(), str.size());
}
}
return 0;
}