PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] How to catch and deal with "WebSocket is already in CLOSING or CLOSED state" in Node

 October 22, 2022     javascript, node.js, sockets, websocket     No comments   

Issue

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?


Solution

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



Answered By - yeya
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing