-
Notifications
You must be signed in to change notification settings - Fork 1
/
demo.cpp
202 lines (176 loc) · 5.23 KB
/
demo.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#define _CRT_SECURE_NO_WARNINGS 1
#include "phttp.h"
#include <thread>
#include <string.h>
#ifdef _WIN32
#pragma comment(lib, "Ws2_32.lib")
#else
#include <signal.h>
#endif
static phttp::Server* SingleServer;
static const char* Script = R"(
var doHeavyFetch = false;
var doWebSocket = true;
if (doHeavyFetch) {
// fetch heavy payload
var r = new XMLHttpRequest();
r.open('GET', '/heavy');
r.send();
}
if (doWebSocket) {
// open websocket
var ws = new WebSocket("ws://localhost:8080");
var tick = 0;
var sendWS = function() {
// stop if socket !open
if (ws.readyState != 1)
return;
var msg = "Hello!";
if (tick % 100 == 0) {
for (var i = 0; i < 5000; i++) {
msg += "very long message " + i + ", ";
}
} else if (tick % 20 == 0) {
for (var i = 0; i < 100; i++) {
msg += "long message " + i + ", ";
}
} else {
msg = "Hello!" + tick;
for (var i = 0; i < tick % 11; i++)
msg += ".";
}
//var msg = "";
//for (var i = 0; i < tick % 11; i++)
// msg += ".";
console.log("sending..." + tick + ", " + ws.readyState);
ws.send(msg);
console.log("sent" + tick);
tick++;
setTimeout(function() {
sendWS();
}, 100);
};
ws.addEventListener('open', function() {
sendWS();
});
ws.addEventListener('message', function(ev) {
console.log("Server said: ", ev.data);
});
}
)";
#ifdef _WIN32
BOOL ctrl_handler(DWORD ev) {
if (ev == CTRL_C_EVENT && SingleServer != nullptr) {
SingleServer->Stop();
return TRUE;
}
return FALSE;
}
void setup_ctrl_c_handler() {
SetConsoleCtrlHandler((PHANDLER_ROUTINE) ctrl_handler, TRUE);
}
void sleepnano(int64_t nanoseconds) {
YieldProcessor();
Sleep((DWORD)(nanoseconds / 1000000));
}
#else
void signal_handler(int sig) {
if (SingleServer != nullptr)
SingleServer->Stop();
}
void setup_ctrl_c_handler() {
struct sigaction sig;
sig.sa_handler = signal_handler;
sigemptyset(&sig.sa_mask);
sig.sa_flags = 0;
sigaction(SIGINT, &sig, nullptr);
}
void sleepnano(int64_t nanoseconds) {
timespec t;
t.tv_nsec = nanoseconds % 1000000000;
t.tv_sec = (nanoseconds - t.tv_nsec) / 1000000000;
nanosleep(&t, nullptr);
}
#endif
int main(int argc, char** argv) {
#ifdef _WIN32
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
setup_ctrl_c_handler();
phttp::Initialize();
phttp::Server server;
// We treat wsID as atomic here, mutating it from multiple threads. In production, use std::atomic<int64_t> instead.
int64_t wsID = 0;
std::thread wsSender([&wsID, &server] {
// Wait until a web socket connection is made
while (wsID == 0) {
sleepnano(100 * 1000 * 1000);
if (server.StopSignal)
break;
}
// Here we send web socket messages from another thread.
for (size_t i = 0; i < 100 && wsID != 0; i++) {
char buf[100];
sprintf(buf, "tick tock %d", (int) i);
if (!server.SendWebSocket(wsID, phttp::RequestType::WebSocketText, buf, strlen(buf)))
break;
sleepnano(200 * 1000 * 1000);
}
});
auto handler = [&server, &wsID](phttp::Response& w, phttp::RequestPtr r) {
if (r->IsWebSocketUpgrade()) {
// Before deciding to return OK, you must validate the Origin header for CORS sake.
// To upgrade the connection, send a 200, and populate the Sec-WebSocket-Protocol header,
// making it one of the proposed protocols that the client requested.
w.Status = 200;
// assume client proposed only one protocol, and if so, reply that we're accepting it
if (r->Header("Sec-WebSocket-Protocol") != "")
w.SetHeader("Sec-WebSocket-Protocol", r->Header("Sec-WebSocket-Protocol"));
wsID = r->ConnectionID;
return;
}
if (r->Type == phttp::RequestType::Http) {
if (r->Path == "/") {
w.SetHeader("Content-Type", "text/html; charset=utf-8");
w.SetHeader("Content-Encoding", "utf-8");
w.Body = "<!DOCTYPE HTML>\n<head><link rel='stylesheet' href='a.css'></head>\n<body>Hello phttp!</body>\n";
w.Body += "<script>";
w.Body += Script;
w.Body += "</script>";
} else if (r->Path == "/a.css") {
w.SetHeader("Content-Type", "text/css");
w.Body = "body { color: #0a0 }";
} else if (r->Path == "/heavy") {
// Send 32 MB payload
w.SetHeader("Content-Type", "text/plain");
w.Body = "12345678901234567890123456789012"; // 32 bytes
for (int i = 0; i < 20; i++)
w.Body += w.Body;
} else if (r->Path == "/seppuku") {
w.Body += "Stopping server-> The client may never receive this message\n";
server.Stop();
} else {
w.Body += "Unknown path: " + r->Path + "\n";
w.Body += "Query:\n";
for (auto p : r->Query)
w.Body += "" + p.first + ":" + p.second + "\n";
}
} else if (r->Type == phttp::RequestType::WebSocketClose) {
printf("websocket closed by client\n");
wsID = 0;
} else if (r->Type == phttp::RequestType::WebSocketText) {
// This demonstrates sending a reply to a websocket frame.
// WebSockets are not typically used in a request/response manner,
// but for the purposes of demonstration, we do that here.
printf("websocket in: %s\n", r->Frame().c_str());
server.SendWebSocket(r->ConnectionID, phttp::RequestType::WebSocketText, "hi from websocket!");
}
};
server.LogAllEvents = true;
SingleServer = &server;
server.ListenAndRun("127.0.0.1", 8080, handler);
phttp::Shutdown();
wsSender.join();
SingleServer = nullptr;
return 0;
}