Add upgrade handler

This commit is contained in:
Alex Hultman
2020-06-01 15:45:03 +02:00
parent 1699b214c5
commit 4be90c0114
3 changed files with 37 additions and 2 deletions
+8
View File
@@ -8,6 +8,7 @@ int main() {
/* ws->getUserData returns one of these */
struct PerSocketData {
/* Fill with user data */
int something;
};
/* Keep in mind that uWS::SSLApp({options}) is the same as uWS::App() when compiled without SSL support.
@@ -24,8 +25,15 @@ int main() {
.idleTimeout = 10,
.maxBackpressure = 1 * 1024 * 1204,
/* Handlers */
.upgrade = [](auto *res, atuo *req) {
std::cout << "Upgrade now!" << std::endl;
/* Pass user data from upgrade to open handler here */
//res.upgrade({.something = 15}, req);
},
.open = [](auto *ws, auto *req) {
/* Open event here, you may access ws->getUserData() which points to a PerSocketData struct */
std::cout << "Something is: " << ws->getUserData().something << std::endl;
},
.message = [](auto *ws, std::string_view message, uWS::OpCode opCode) {
ws->send(message, opCode);
+24 -2
View File
@@ -1,5 +1,5 @@
/*
* Authored by Alex Hultman, 2018-2019.
* Authored by Alex Hultman, 2018-2020.
* Intellectual property of third-party.
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -87,7 +87,8 @@ public:
CompressOptions compression = DISABLED;
int maxPayloadLength = 16 * 1024;
int idleTimeout = 120;
int maxBackpressure = 1 * 1024 * 1204;
int maxBackpressure = 1 * 1024 * 1024;
fu2::unique_function<void(HttpResponse<SSL> *, HttpRequest *)> upgrade = nullptr;
fu2::unique_function<void(uWS::WebSocket<SSL, true> *, HttpRequest *)> open = nullptr;
fu2::unique_function<void(uWS::WebSocket<SSL, true> *, std::string_view, uWS::OpCode)> message = nullptr;
fu2::unique_function<void(uWS::WebSocket<SSL, true> *)> drain = nullptr;
@@ -153,6 +154,27 @@ public:
/* If we have this header set, it's a websocket */
std::string_view secWebSocketKey = req->getHeader("sec-websocket-key");
if (secWebSocketKey.length() == 24) {
/* Emit upgrade handler */
if (behavior.upgrade) {
// a regular HttpResponse does not know about UserData or any of the Websocket upgrade procedure
behavior.upgrade(res, req);
// if upgrade handler does not upgrade or end within the callback, lift a token?
// handle close here
}
/* Note: OpenSSL can be used here to speed this up somewhat */
char secWebSocketAccept[29] = {};
WebSocketHandshake::generate(secWebSocketKey.data(), secWebSocketAccept);
+5
View File
@@ -172,6 +172,11 @@ public:
using Super::getRemoteAddress;
/* Manually upgrade to WebSocket, called in upgrade handler of a WebSocket route */
/*void upgrade() {
}*/
/* Note: Headers are not checked in regards to timeout.
* We only check when you actively push data or end the request */