How to catch and deal with "WebSocket is already in CLOSING or CLOSED state" in Node : <p>I've been searching for a solution to the issue "WebSocket is already in CLOSING or CLOSED state" and found this:</p>

<ol>
<li><a href="https://stackoverflow.com/questions/40259972/meteor-websocket-is-already-in-closing-or-closed-state-error">Meteor WebSocket is already in CLOSING or CLOSED state error</a></li>
<li><a href="https://stackoverflow.com/questions/25266009/websocket-is-already-in-closing-or-closed-state">WebSocket is already in CLOSING or CLOSED state.</a></li>
</ol>

<p>Answer #1 is for strictly related to Meteor and #2 has no answers... I have a Node server app with a socket:</p>

<pre><code>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);
  });
});
</code></pre>

<p>And clients connect like this:</p>

<pre><code>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);
});
</code></pre>

<p>However after a few minutes, clients randomly disconnect and the function</p>

<pre><code>socket.send(JSON.stringify(data));
</code></pre>

<p>Will then throw a "WebSocket is already in CLOSING or CLOSED state.".</p>

<p>I am looking for a way to detect and deal these disconnections and immediately attempt to connect again.</p>

<p><strong>What is the most correct and efficient way to do this?</strong></p>
