Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i make broadcast with express-ws ? #140

Open
peterkowalsky333 opened this issue Nov 11, 2020 · 2 comments
Open

How can i make broadcast with express-ws ? #140

peterkowalsky333 opened this issue Nov 11, 2020 · 2 comments

Comments

@peterkowalsky333
Copy link

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 ?

@aral
Copy link

aral commented Jan 8, 2021

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

@Perodactyl
Copy link

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)
    })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants