Sometimes, when i run broadcasting with following code:
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
// Logger.info('Sending message', data);
client.send(JSON.stringify(data));
});
};
it looks like some client is closed, throwing an error.
Is there a way to test if a client is open or closed?
if (client.readyState === client.OPEN) {
// open
}
Btw, it looks like if a client disconnect, it is not automatically removed from the list of clients.
I have to run a check on broadcast.
Is it the expected behavior?
My main question is: why a client is closed? it is because it disconnected for any reason but it is still in the list of clients?
Or is there any other reason why a client is in the list of clients but its state is not open?
Will some client loose messages if I ignore the error?
If I remember correcly, if you ignore the error, the server will crash because you're trying to write to a not-ready-to-receive-info-socket.
As for the list of clients, it should clean itself (ref).
Well, I am trying to figure out where the error happens.
I am using version v0.7.2, that still removes the client on close event. So this version should be fine.
My code runs a ws.close() instruction when the client is not authorized anymore (according to my authentication system).
So even when the client is not authorized, then the client should be removed from the list.
But apparently there is still something that puts the state of client as not ready, but the client is not removed from the list clients.
Do you have any recommendation on which could be the cause?
Is there any other not handled event that could cause this issue (aka something that closes the client, but not through the method 'close')?
Well, cleanupWebsocketResources (ref) calls emit('close'), maybe you could try to check if that's being called and check the params?
Other than that, I'd try against a newer ws version.
@bitliner a client is removed from the list of clients when the ready state is changed to CLOSED and the close event is emitted.
After calling ws.close() a client changes its ready state to CLOSING and starts a closing handshake. This can take some time and if you try to send data when the ready state is CLOSING you get an error.
As suggested by @ericmdantas check if the ready state is OPEN before sending data and use a newer version of ws :)
Most helpful comment