All WebSocket connections lost when someone refresh a page

Hi guys,

I’ve this simple node.js server app structure. It broadcasts message of a client to all connected clients. However, those connections have been lost when someone refresh a page. Anyone can point out what wrong with my code? How can I keep all connections connected.

var WebSocketServer = require(‘ws’).Server;

var wsServer = new WebSocketServer({ port : 8080 }),
clients = ;

wsServer.on(‘connection’, function(ws) {
clients.push(ws);

ws.on(‘message’, function(message, flags) {
for(var i = 0, j = clients.length; i < j; i += 1) {
var xx = clients[i];
}
if (typeof message === ‘string’) {
var json = JSON.parse(message);
switch(json.type) {
case “msg”:
broadcast.data(xx, message);
break;
case “data”:
case “demo”:
// return;
break;
}
}
});

ws.on(‘close’, function(message) {
var index = clients.indexOf(ws);
if (index !== -1) {
clients.splice(index, 1);
}
});
});

// Broadcast messages to all connected clients
var broadcast = {
data: function(xi, message) {
var that = this;
this.xi = xi;
this.message = message;
this.data.prototype = function() { that.send(this.xi, this.message); }
this.data.prototype(this.xi, this.message);
},
send: function(){
this.xi.send(this.message, {
mask: false
});
}
};

Thanks

It’s not a problem with your code, it’s just the way WebSocket’s work… if you refresh or close the page, the connection is broken. As far as I know, there’s currently no way around this.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.