-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathChunkedResponse.cpp
More file actions
57 lines (44 loc) · 1.38 KB
/
ChunkedResponse.cpp
File metadata and controls
57 lines (44 loc) · 1.38 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
#include "App.h"
/* This example demonstrates a large chunked response streamed with tryWrite. */
#include <cstdint>
#include <memory>
#include <string>
namespace {
const std::string payload(16 * 1024 * 1024, 'x');
struct ResponseState {
bool aborted = false;
};
template <bool SSL>
bool tryWriteLoop(uWS::HttpResponse<SSL> *res, ResponseState *state) {
if (state->aborted) {
return true;
}
uintmax_t sent = res->getWriteOffset();
std::string_view remaining = payload;
remaining.remove_prefix((size_t) sent);
return res->tryWrite(remaining, true);
}
}
int main() {
uWS::SSLApp({
.key_file_name = "misc/key.pem",
.cert_file_name = "misc/cert.pem",
.passphrase = "1234"
}).get("/*", [](auto *res, auto */*req*/) {
auto state = std::make_shared<ResponseState>();
res->writeHeader("Content-Type", "application/octet-stream");
res->onAborted([state]() {
state->aborted = true;
});
if (!tryWriteLoop(res, state.get())) {
res->onWritable([res, state](uintmax_t) {
return tryWriteLoop(res, state.get());
});
}
}).listen(3000, [](auto *listen_socket) {
if (listen_socket) {
std::cout << "Listening on port " << 3000 << std::endl;
}
}).run();
std::cout << "Failed to listen on port 3000" << std::endl;
}