Enhance WebSocket server ping/pong handling and timeout settings

- Introduce handling for LWS_CALLBACK_RECEIVE_PONG to manage Pong frames received from clients.
- Update the WebSocketUserData structure to increase MAX_PING_TIMEOUTS from 3 to 5, allowing more attempts before disconnection.
- Extend PONG_TIMEOUT_SECONDS from 10 to 60 to accommodate longer response times from browsers.
- Modify ping handling to send a WebSocket Ping frame instead of a text message for better protocol compliance.
This commit is contained in:
Torsten Schulz (local)
2025-11-18 10:32:55 +01:00
committed by Torsten (PC)
parent 0eb3a78332
commit e3f46d775a
2 changed files with 16 additions and 9 deletions

View File

@@ -250,16 +250,23 @@ int WebSocketServer::wsCallback(struct lws *wsi,
std::cout << "Client-Adresse: " << client_addr << std::endl;
break;
}
case LWS_CALLBACK_RECEIVE_PONG:
// WebSocket Pong-Frame empfangen (automatische Antwort auf Ping)
ud->pongReceived = true;
ud->lastPongTime = std::chrono::steady_clock::now();
ud->pingTimeoutCount = 0;
// std::cout << "Pong-Frame von Client empfangen" << std::endl;
return 0;
case LWS_CALLBACK_RECEIVE: {
std::string msg(reinterpret_cast<char*>(in), len);
std::cout << "WebSocket-Nachricht empfangen: " << msg << std::endl;
// Pong-Antwort behandeln
// Fallback: Pong als Text-Nachricht (für Kompatibilität)
if (msg == "pong") {
ud->pongReceived = true;
ud->lastPongTime = std::chrono::steady_clock::now();
ud->pingTimeoutCount = 0;
std::cout << "Pong von Client empfangen" << std::endl;
std::cout << "Pong (Text) von Client empfangen" << std::endl;
break;
}
@@ -313,13 +320,13 @@ int WebSocketServer::wsCallback(struct lws *wsi,
}
}
} else {
// Ping senden
// WebSocket Ping-Frame senden (nicht Text-Nachricht!)
ud->lastPingTime = std::chrono::steady_clock::now();
ud->pongReceived = false;
unsigned char buf[LWS_PRE + 4];
memcpy(buf + LWS_PRE, "ping", 4);
lws_write(wsi, buf + LWS_PRE, 4, LWS_WRITE_TEXT);
// std::cout << "Ping an Client gesendet" << std::endl;
// Leeres Ping-Frame senden (Browser antworten automatisch mit Pong)
unsigned char buf[LWS_PRE + 0];
lws_write(wsi, buf + LWS_PRE, 0, LWS_WRITE_PING);
// std::cout << "Ping-Frame an Client gesendet" << std::endl;
}
break;
}

View File

@@ -25,9 +25,9 @@ struct WebSocketUserData {
std::chrono::steady_clock::time_point lastPingTime;
std::chrono::steady_clock::time_point lastPongTime;
int pingTimeoutCount = 0;
static constexpr int MAX_PING_TIMEOUTS = 3;
static constexpr int MAX_PING_TIMEOUTS = 5; // Mehr Versuche bevor Trennung
static constexpr int PING_INTERVAL_SECONDS = 30;
static constexpr int PONG_TIMEOUT_SECONDS = 10;
static constexpr int PONG_TIMEOUT_SECONDS = 60; // Längeres Timeout (Browser können länger brauchen)
};
class Worker; // forward