Skip to content
Advertisement

How to catch and deal with “WebSocket is already in CLOSING or CLOSED state” in Node

I’ve been searching for a solution to the issue “WebSocket is already in CLOSING or CLOSED state” and found this:

  1. Meteor WebSocket is already in CLOSING or CLOSED state error
  2. WebSocket is already in CLOSING or CLOSED state.

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement