I am using Einaros WS module with Node JS on one computer (server)
and it works okay when I connect using another (client)
computer.
If I plug the network cable, the ws.on('close', function()...
is not firing and am looking for advice whether:
I have to implement my own ping/pong, or
There is a built-in feature to handle this automatically.
Node.js exposes a server.timeout property that determines the amount of inactivity on a connection socket before it is assumed to have timed out. It is set to 0 by default which means no timeout, giving the possibility of a connection that hangs forever. To fix this, you must set server.timeout to a more suitable value:
For example, in Firefox this timeout is set to 90 seconds by default, but in Chromium, it is 300 seconds. In Node.js, no default timeout is set for fetch () requests, but the newly added AbortSignal.timeout () API provides an easy way to cancel a fetch () request when a timeout is reached.
What Is Err_Connection_Timed_Out Error The connection timed out error isn’t a harmful error or any infected file that can cause harm to your system. This message is mainly the notification that the system is unable to set up a connection with the server.
Promises are the recommended way to perform asynchronous operations in Node.js, but there is currently no API to cancel one if it is not fulfilled within a period of time.
Einaros WS does have the ability to send Ping and Pong frames that are understood by most browsers and socket frameworks out there. I've tested with Socket Rocket on iOS and it had no issues understanding Ping frames for Einaros. You do have to come up with the application specific logic of how often to ping, as well as how many missed pongs you will tolerate. Einaros WS has ping() and pong() functions to send pings or pongs. You listen to the "pong" event to know when you received a response from the clients. Here's how I do this in my code:
wss.on("connection", function(ws) {
console.log("websocket connection open");
ws.pingssent = 0;
var interval = setInterval(function() {
if (ws.pingssent >= 2) {// how many missed pings you will tolerate before assuming connection broken.
ws.close();
} else {
ws.ping();
ws.pingssent++;
}
}, 75*1000);// 75 seconds between pings
ws.on("pong", function() { // we received a pong from the client.
ws.pingssent = 0; // reset ping counter.
});
});
In the case of Socket Rocket, no code was required on the client side. So compatible browsers and clients will respond with Pongs automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With