I am using this library to build an online game. Some connection will be closed intentionally when the player loses the game. But every time I send some message on the server if the readyState is not WebSocket.OPEN it will give an error saying "Not Opened". So my code is full of state checking condition clauses. Is it possible to check this state less often? For example, giving some extra configs in the send command to enable checking this state automatically or go without checking it.
You can add a callback. It will be called with an error if the readyState is not OPEN. If you want to ignore the error you can use a noop function.
Thanks I know there is a callback. But I need a check before sending the message not after sending it and get a feedback.
The callback is invoked before sending the message when the readyState is not OPEN. See https://github.com/websockets/ws/blob/d7811907ad590cbc7a6354f61dd283e36d1eee4d/lib/WebSocket.js#L353-L357.
Oh nice. I didn't read that carefully.
Closing, feel free to continue discussing on the closed thread.
Now I am using this code:
try {
ws.send(msg, function(error) {
if(error == undefined)
return;
else
logger.debug("Async error:"+error);
});
} catch(e) {
logger.debug("Sync error: " + e);
ws.close();
}
And I have the error listener on the virtual client on the server side:
ws.on('error', function error(event) {
logger.debug(event.err + ' state: ' + ws.readyState);
});
and client side:
ws.onerror = function error(event) {
console.log(event.err + ' state: ' + socket.readyState);
};
On server side:
wss.on('error', function error(err) {
console.log('Error: ' + err.code);
});
Inside wss.on('connection', function(ws, req) {}):
ws.on('error', function(err) {
logger.debug('Found error: ' + err);
});
ws.on('close', function() {
logger.debug('connection closed.');
});
Sometimes the client connection is closed ( I have only one client on a different computer) incidentally while playing the game. But the server keeps running. And the readyState is not opened. What could be the problem?
crazyyi
You're the best!
try {
ws.send(RespuestaToUser, function(error) {
if(error == undefined)
return;
else
Salida = true
});
} catch(e) {
Salida = true
ws.close();
}
Run Perfect!
Most helpful comment
Now I am using this code:
And I have the error listener on the virtual client on the server side:
and client side:
On server side:
Inside
wss.on('connection', function(ws, req) {}):Sometimes the client connection is closed ( I have only one client on a different computer) incidentally while playing the game. But the server keeps running. And the readyState is not opened. What could be the problem?