mirror of
https://github.com/me-no-dev/ESPAsyncWebServer.git
synced 2025-09-30 08:10:56 +02:00
Add example to prevent WS connection if too many clients
This commit is contained in:
@@ -702,8 +702,23 @@ void setup() {
|
|||||||
//
|
//
|
||||||
server.addHandler(&events);
|
server.addHandler(&events);
|
||||||
|
|
||||||
// Run: websocat ws://192.168.4.1/ws
|
// Run in terminal 1: websocat ws://192.168.4.1/ws => stream data
|
||||||
server.addHandler(&ws);
|
// Run in terminal 2: websocat ws://192.168.4.1/ws => stream data
|
||||||
|
// Run in terminal 3: websocat ws://192.168.4.1/ws => should fail:
|
||||||
|
/*
|
||||||
|
❯ websocat ws://192.168.4.1/ws
|
||||||
|
websocat: WebSocketError: WebSocketError: Received unexpected status code (503 Service Unavailable)
|
||||||
|
websocat: error running
|
||||||
|
*/
|
||||||
|
server.addHandler(&ws).addMiddleware([](AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||||
|
if (ws.count() > 2) {
|
||||||
|
// too many clients - answer back immediately and stop processing next middlewares and handler
|
||||||
|
request->send(503, "text/plain", "Server is busy");
|
||||||
|
} else {
|
||||||
|
// process next middleware and at the end the handler
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
#if __has_include("ArduinoJson.h")
|
#if __has_include("ArduinoJson.h")
|
||||||
server.addHandler(jsonHandler);
|
server.addHandler(jsonHandler);
|
||||||
@@ -729,9 +744,9 @@ void loop() {
|
|||||||
}
|
}
|
||||||
if (now - lastWS >= deltaWS) {
|
if (now - lastWS >= deltaWS) {
|
||||||
ws.printfAll("kp%.4f", (10.0 / 3.0));
|
ws.printfAll("kp%.4f", (10.0 / 3.0));
|
||||||
for (auto& client : ws.getClients()) {
|
// for (auto& client : ws.getClients()) {
|
||||||
client.printf("kp%.4f", (10.0 / 3.0));
|
// client.printf("kp%.4f", (10.0 / 3.0));
|
||||||
}
|
// }
|
||||||
lastWS = millis();
|
lastWS = millis();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,11 +2,11 @@
|
|||||||
default_envs = arduino-2, arduino-3, arduino-310, esp8266, raspberrypi
|
default_envs = arduino-2, arduino-3, arduino-310, esp8266, raspberrypi
|
||||||
lib_dir = .
|
lib_dir = .
|
||||||
; src_dir = examples/CaptivePortal
|
; src_dir = examples/CaptivePortal
|
||||||
; src_dir = examples/SimpleServer
|
src_dir = examples/SimpleServer
|
||||||
; src_dir = examples/StreamFiles
|
; src_dir = examples/StreamFiles
|
||||||
; src_dir = examples/Filters
|
; src_dir = examples/Filters
|
||||||
; src_dir = examples/Issue85
|
; src_dir = examples/Issue85
|
||||||
src_dir = examples/Issue162
|
; src_dir = examples/Issue162
|
||||||
|
|
||||||
[env]
|
[env]
|
||||||
framework = arduino
|
framework = arduino
|
||||||
|
Reference in New Issue
Block a user