express-ws icon indicating copy to clipboard operation
express-ws copied to clipboard

How can i make broadcast with express-ws ?

Open peterkowalsky333 opened this issue 5 years ago • 2 comments

In the documentation is writed that with getWss() we can get all clients. But it is not explained how. From the method i get a long object, and i don't know how can i make broadcasting, so messege is send to all clients that are connected to my websocket.

Also in the documentation for -- wsInstance.getWss() --is written:

Note that this list will include all clients, not just those for a specific route - this means that it's often not a good idea to use this for broadcasts, for example.

But the getWss() method is the only one that is pointed to some broadcasting. If it is not good idea then what should we use ?

peterkowalsky333 avatar Nov 11 '20 07:11 peterkowalsky333

Not sure if you still need this but it’s part of what I implemented in my fork a while back: https://github.com/aral/express-ws

aral avatar Jan 08 '21 20:01 aral

When a connection is made, I'd suggest storing the ws parameter in an array. To broadcast, just forEach through them and use ws.send to give each client the data you want to broadcast.

var connections = []
app.ws("/your/ws/path/here", (ws,res)=>{
    connections.push(ws)
    //whatever other stuff here, you could also have it be an object storing stuff about the ws that contains it.
})
function broadcast(message){
    connections.forEach((ws)=>{
        //if the connections are objects with info use something like ws.ws.send()
        ws.send(message)
    })
}

Perodactyl avatar Aug 17 '21 21:08 Perodactyl