7

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.

Jack M.
  • 3,676
  • 5
  • 25
  • 36
  • 1
    Einaros WS module is not built to facilitate any functionality, you should implement it yourself. See [my answer](http://stackoverflow.com/questions/25362613/nodejs-with-einaros-websocket-client-ping-server-vs-server-ping-client/25365579#25365579) for your other question. – mekwall Aug 18 '14 at 14:25

1 Answers1

17

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.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
Praneeth Wanigasekera
  • 946
  • 1
  • 10
  • 16
  • I had one confusion: how to send PONG. This question solved my confusion http://stackoverflow.com/q/10585355/4040525 . Browsers send PONG automatically. also see: https://github.com/websockets/ws/issues/316 – Sourav Ghosh Nov 14 '16 at 17:22
  • Also, use `ws.ping(null,null,true);` otherwise, ws server will throw error if the client is disconnected and server tries to send ping at setinterval time. see: https://github.com/websockets/ws/blob/master/doc/ws.md#websocketpingdata-options-dontfailwhenclosed – Sourav Ghosh Nov 14 '16 at 17:42