forked from IronsDu/brynet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.cpp
More file actions
81 lines (73 loc) · 2.66 KB
/
Copy pathHttpServer.cpp
File metadata and controls
81 lines (73 loc) · 2.66 KB
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
#include <brynet/base/AppStatus.hpp>
#include <brynet/net/http/HttpFormat.hpp>
#include <brynet/net/http/HttpService.hpp>
#include <brynet/net/http/WebSocketFormat.hpp>
#include <brynet/net/wrapper/HttpServiceBuilder.hpp>
#include <brynet/net/wrapper/ServiceBuilder.hpp>
#include <condition_variable>
#include <iostream>
#include <string>
using namespace brynet;
using namespace brynet::net;
using namespace brynet::net::http;
int main(int argc, char** argv)
{
if (argc != 3)
{
fprintf(stderr, "Usage: <listen port> <net work thread num>\n");
exit(-1);
}
const auto port = std::atoi(argv[1]);
auto service = IOThreadTcpService::Create();
service->startWorkerThread(atoi(argv[2]));
auto httpEnterCallback = [](const HTTPParser& httpParser,
const HttpSession::Ptr& session) {
(void) httpParser;
HttpResponse response;
//std::cout << "method:" << http_method_str(static_cast<http_method>(httpParser.method())) << std::endl;
response.setBody(std::string("<html>hello world </html>"));
if (httpParser.isKeepAlive())
{
response.addHeadValue("Connection", "Keep-Alive");
session->send(response.getResult());
}
else
{
response.addHeadValue("Connection", "Close");
session->send(response.getResult(), [session]() {
session->postShutdown();
});
}
};
auto wsEnterCallback = [](const HttpSession::Ptr& httpSession,
WebSocketFormat::WebSocketFrameType opcode,
const std::string& payload) {
std::cout << "frame enter of type:" << int(opcode) << std::endl;
std::cout << "payload is:" << payload << std::endl;
// echo frame
httpSession->send(WebSocketFormat::wsFrameBuild(payload));
};
wrapper::HttpListenerBuilder listenBuilder;
listenBuilder
.WithService(service)
.AddSocketProcess([](TcpSocket& socket) {
socket.setNodelay();
})
.WithMaxRecvBufferSize(1024)
.WithAddr(false, "0.0.0.0", port)
.WithReusePort()
.WithEnterCallback([httpEnterCallback, wsEnterCallback](const HttpSession::Ptr& httpSession, HttpSessionHandlers& handlers) {
handlers.setHttpEndCallback(httpEnterCallback);
handlers.setWSCallback(wsEnterCallback);
})
.asyncRun();
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
if (brynet::base::app_kbhit())
{
break;
}
}
return 0;
}