socm_
socm_

Reputation: 787

Why websocket server closes connections?

enter image description here

I have websocket nodejs server with ~2000 concurrent connections and server closes them periodically. I don't know the reason. I catch it in my client code

 this.ws.onclose = function(){
        //try to reconnect in 5 seconds
        console.log("WS CLOSED. RECONNECT IN 5 SECS");
        setTimeout(function(){self.startNative()}, 5000);
    };

I start server with following code

var WebSocketServer = require('ws');

//start websockets server
var webSocketServer = new WebSocketServer.Server({port: config.port2}, function () {
    console.log("Native websocket server process running on " + config.port2);
});

//websockets connection
webSocketServer.on('connection', function(ws, req) {
    ws.on('close', function() {
        //somecode
    });

What can cause it ?

Upvotes: 0

Views: 1267

Answers (1)

John Zwinck
John Zwinck

Reputation: 249642

Middleboxes on the internet will close connections that have seen no data for a long time (many minutes or hours). You can resolve this by sending a "heartbeat" packet periodically, say once per five minutes.

It does not matter which direction originates the heartbeats, and the other side does not need to explicitly reply (but it could). If the server is the one who sends heartbeats, this will also help the server to prune dead connections sooner.

Upvotes: 2

Related Questions