I've been searching for a solution to the issue "WebSocket is already in CLOSING or CLOSED state" and found this:
Answer #1 is for strictly related to Meteor and #2 has no answers... I have a Node server app with a socket:
const WebSocket = require('ws'); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(socket) { socket.on('message', function incoming(data) { console.log('Incoming data ', data); }); });
And clients connect like this:
const socket = new WebSocket('ws://localhost:3090'); //Create WebSocket connection //Connection opened socket.addEventListener('open', function(event) { console.log("Connected to server"); }); //Listen to messages socket.addEventListener('message', function(event) { console.log('Message from server ', event); });
However after a few minutes, clients randomly disconnect and the function
socket.send(JSON.stringify(data));
Will then throw a "WebSocket is already in CLOSING or CLOSED state.".
I am looking for a way to detect and deal these disconnections and immediately attempt to connect again.
What is the most correct and efficient way to do this?
You can check if a WebSocket is disconnected by doing either of the following: Specifying a function to the WebSocket. onclose event handler property, or; Using addEventListener to listen to the close event.
The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.
In the search field, enter websocket . From the search results, click WebSocket Connection Status.
In this code what it means is that ws. close() was called (by user code) before the connection was even given a chance to be established. So, the cause of this error is if code attempts to close the WebSocket connection before it's had a chance to actually connect.
The easiest way is to check if the socket is open or not before sending.
For example - write a simple function:
function isOpen(ws) { return ws.readyState === ws.OPEN }
Then - before any socket.send
make sure it is open:
if (!isOpen(socket)) return; socket.send(JSON.stringify(data));
You can also rewrite the send
function like this answer but in my way you can log this situations.
And, for your second request
immediately attempt to connect again
There is no way you can do it from the server.
The client code should monitor the WebSocket state and apply reconnect method based on your needs.
For example - check this VueJS library that do it nicely. Look at Enable ws reconnect automatically section
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With