ws.close() or ws.terminate() doesn't remove socket object from wss.

Created on 20 Sep 2018  路  1Comment  路  Source: websockets/ws

I am using node wslibrary for some TCP communication with my node server.

when new connection establishes wssstores it. But my requirement is at some point I want to close the connection. I tried with both ws.close and ws.terminate. Both closes the connection and changes the readystate to closed. But wss still has client socket details. when same socket is connected again wss will have duplicate sockets, which makes my single client receive same message two times.

Below is my code

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 3333 });

wss.on('connection', function connection(ws) {
        ws.on('message', function incoming(message) {
            console.log(message);
        });
});

wss.clients.forEach(function each(client) {
        client.send(JSON.stringify("some message here"), () => {
            console.log("message sent successfully");
        });
})

wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.close();
        }
});

How do I remove socket from wss.clients. Thanks in advance

Most helpful comment

Clients are removed from the clients set as soon as the 'close' event is emitted on the WebSocket instance.

See https://github.com/websockets/ws/blob/7d7ddfd2e2e010bbdba6acfd9b8fb0f0ab79c951/lib/websocket-server.js#L292.

>All comments

Clients are removed from the clients set as soon as the 'close' event is emitted on the WebSocket instance.

See https://github.com/websockets/ws/blob/7d7ddfd2e2e010bbdba6acfd9b8fb0f0ab79c951/lib/websocket-server.js#L292.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Globik picture Globik  路  3Comments

ImBundle picture ImBundle  路  3Comments

quesurifn picture quesurifn  路  3Comments

dcflow picture dcflow  路  4Comments

pacmac picture pacmac  路  3Comments