HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
877 stars 142 forks source link

getWss().clients is an empty set #112

Open Yourz opened 5 years ago

Yourz commented 5 years ago

`const express = require('express'); const http = require('http'); const ws = require('express-ws'); const app = express(); const server = http.createServer(app); const wss = ws(app, server);

app.ws('/lock/:id', function(ws, req) { let author = null; const WriteLock = require('./utils/writeLock'); const lock = new WriteLock(req.params.id); ws.on('message', function(msg) { author = JSON.parse(msg); lock.enter(author); }); ws.onclose = function (){ if (author) { lock.exit(author); console.log(wss.getWss().clients); wss.getWss().clients.forEach(client => { console.log(client); }) } }; })`

websocket looks fine with me(status 101, on hook works fine and message transfer correctly), but i got empty clients set.

kuria-wachira25 commented 4 years ago

I had the same problem solved it this way so i decided to handle this problem in somehow a manual way:

  1. Set a global variable clients which is of type set as follows: const clients = new Set(); (Can be exported using module.exports if you plan to broadcast from middlewares that are in multiple files)

  2. Make your middleware as follows:

app.ws('/',(ws,req) =>
{
    //Add client to Set. NB: The list being a Set will help to avoid adding duplicate clients
    clients.add(ws)

    ws.on('close',() =>
    {   
        //Remove client from Set once their connection is closed
        clients.delete(ws)
    })

    ws.on('message',(msg) =>
    {
        //Write you websocket logic here
    }
};
  1. Broadcast message to all clients
clients.forEach(client =>
{
    client.send(message);
});