Skip to content

Commit d1aacea

Browse files
committed
Add Precompress example and basic support
1 parent b9b59b2 commit d1aacea

File tree

3 files changed

+101
-8
lines changed

3 files changed

+101
-8
lines changed

build.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ int main(int argc, char **argv) {
99
char *CXX = strncpy(calloc(1024, 1), or_else(getenv("CXX"), "g++"), 1024);
1010
char *EXEC_SUFFIX = strncpy(calloc(1024, 1), maybe(getenv("EXEC_SUFFIX")), 1024);
1111

12-
char *EXAMPLE_FILES[] = {"EchoBody", "HelloWorldThreaded", "Http3Server", "Broadcast", "HelloWorld", "Crc32", "ServerName",
12+
char *EXAMPLE_FILES[] = {"Precompress", "EchoBody", "HelloWorldThreaded", "Http3Server", "Broadcast", "HelloWorld", "Crc32", "ServerName",
1313
"EchoServer", "BroadcastingEchoServer", "UpgradeSync", "UpgradeAsync", "ParameterRoutes"};
1414

1515
strcat(CXXFLAGS, " -march=native -O3 -Wpedantic -Wall -Wextra -Wsign-conversion -Wconversion -std=c++20 -Isrc -IuSockets/src");

examples/Precompress.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include "App.h"
2+
3+
int main() {
4+
/* ws->getUserData returns one of these */
5+
struct PerSocketData {
6+
/* Fill with user data */
7+
};
8+
9+
/* Keeping track of last precompressed message both in original and compressed format */
10+
std::string originalMessage;
11+
std::string compressedMessage;
12+
std::mutex m;
13+
14+
/* For demo, we create a thread that will update the precompressed message every second */
15+
std::thread t2([&originalMessage, &compressedMessage, &m]() {
16+
uWS::ZlibContext zlibContext;
17+
uWS::DeflationStream compressor(uWS::DEDICATED_COMPRESSOR);
18+
int counter = 0;
19+
20+
while (true) {
21+
counter++;
22+
23+
m.lock();
24+
originalMessage = "Hello you are looking at message number " + std::to_string(counter) + " and this text should be precompressed";
25+
compressedMessage = compressor.deflate(&zlibContext, {originalMessage.data(), originalMessage.length()}, true);
26+
m.unlock();
27+
28+
std::this_thread::sleep_for(std::chrono::milliseconds(500));
29+
}
30+
31+
});
32+
33+
uWS::App().ws<PerSocketData>("/*", {
34+
/* You must only use SHARED_COMPRESSOR with precompression (can't use dedicated_compressor) */
35+
.compression = uWS::CompressOptions(uWS::SHARED_COMPRESSOR | uWS::DEDICATED_DECOMPRESSOR),
36+
/* Handlers */
37+
.upgrade = nullptr,
38+
.open = [](auto */*ws*/) {
39+
/* Open event here, you may access ws->getUserData() which points to a PerSocketData struct */
40+
41+
},
42+
.message = [&originalMessage, &compressedMessage, &m](auto *ws, std::string_view message, uWS::OpCode opCode) {
43+
44+
/* First respond by echoing what they send us, without compression */
45+
ws->send(message, opCode, false);
46+
47+
/* This should be wrapped up into ws->sendPrepared(PreparedMessage) in the future, experimental for now */
48+
m.lock();
49+
if (ws->hasNegotiatedCompression() && compressedMessage.length() < originalMessage.length()) {
50+
std::cout << "Responding with precompressed message saving " << (originalMessage.length() - compressedMessage.length()) << " bytes" << std::endl;
51+
ws->send({compressedMessage.data(), compressedMessage.length()}, uWS::OpCode::TEXT, uWS::CompressFlags::ALREADY_COMPRESSED);
52+
} else {
53+
ws->send({originalMessage.data(), originalMessage.length()}, uWS::OpCode::TEXT);
54+
}
55+
m.unlock();
56+
},
57+
.dropped = [](auto */*ws*/, std::string_view /*message*/, uWS::OpCode /*opCode*/) {
58+
/* A message was dropped due to set maxBackpressure and closeOnBackpressureLimit limit */
59+
},
60+
.drain = [](auto */*ws*/) {
61+
/* Check ws->getBufferedAmount() here */
62+
},
63+
.ping = [](auto */*ws*/, std::string_view) {
64+
/* Not implemented yet */
65+
},
66+
.pong = [](auto */*ws*/, std::string_view) {
67+
/* Not implemented yet */
68+
},
69+
.close = [](auto */*ws*/, int /*code*/, std::string_view /*message*/) {
70+
/* You may access ws->getUserData() here */
71+
}
72+
}).listen(9001, [&t2](auto *listen_socket) {
73+
if (listen_socket) {
74+
std::cout << "Listening on port " << 9001 << std::endl;
75+
}
76+
}).run();
77+
}

src/WebSocket.h

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@
2727

2828
namespace uWS {
2929

30+
/* Experimental */
31+
enum CompressFlags : int {
32+
NO_ACTION,
33+
COMPRESS,
34+
ALREADY_COMPRESSED
35+
};
36+
3037
template <bool SSL, bool isServer, typename USERDATA>
3138
struct WebSocket : AsyncSocket<SSL> {
3239
template <bool> friend struct TemplatedApp;
@@ -87,9 +94,15 @@ struct WebSocket : AsyncSocket<SSL> {
8794
return send(message, CONTINUATION, compress, true);
8895
}
8996

97+
/* Experimental */
98+
bool hasNegotiatedCompression() {
99+
WebSocketData *webSocketData = (WebSocketData *) Super::getAsyncSocketData();
100+
return webSocketData->compressionStatus == WebSocketData::ENABLED;
101+
}
102+
90103
/* Send or buffer a WebSocket frame, compressed or not. Returns BACKPRESSURE on increased user space backpressure,
91104
* DROPPED on dropped message (due to backpressure) or SUCCCESS if you are free to send even more now. */
92-
SendStatus send(std::string_view message, OpCode opCode = OpCode::BINARY, bool compress = false, bool fin = true) {
105+
SendStatus send(std::string_view message, OpCode opCode = OpCode::BINARY, int compress = false, bool fin = true) {
93106
WebSocketContextData<SSL, USERDATA> *webSocketContextData = (WebSocketContextData<SSL, USERDATA> *) us_socket_context_ext(SSL,
94107
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
95108
);
@@ -145,12 +158,15 @@ struct WebSocket : AsyncSocket<SSL> {
145158

146159
/* Check and correct the compress hint. It is never valid to compress 0 bytes */
147160
if (message.length() && opCode < 3 && webSocketData->compressionStatus == WebSocketData::ENABLED) {
148-
LoopData *loopData = Super::getLoopData();
149-
/* Compress using either shared or dedicated deflationStream */
150-
if (webSocketData->deflationStream) {
151-
message = webSocketData->deflationStream->deflate(loopData->zlibContext, message, false);
152-
} else {
153-
message = loopData->deflationStream->deflate(loopData->zlibContext, message, true);
161+
/* If compress is 2 (IS_PRE_COMPRESSED), skip this step (experimental) */
162+
if (compress != CompressFlags::ALREADY_COMPRESSED) {
163+
LoopData *loopData = Super::getLoopData();
164+
/* Compress using either shared or dedicated deflationStream */
165+
if (webSocketData->deflationStream) {
166+
message = webSocketData->deflationStream->deflate(loopData->zlibContext, message, false);
167+
} else {
168+
message = loopData->deflationStream->deflate(loopData->zlibContext, message, true);
169+
}
154170
}
155171
} else {
156172
compress = false;

0 commit comments

Comments
 (0)