Open Yourz opened 5 years ago
I had the same problem solved it this way so i decided to handle this problem in somehow a manual way:
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)
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
}
};
clients.forEach(client =>
{
client.send(message);
});
`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.