Created
April 4, 2016 22:37
-
-
Save hugosp/5eeb2a375157625e21d33d75d10574df to your computer and use it in GitHub Desktop.
Minimal express-ws broadcast to all clients
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var expressWs = require('express-ws'); | |
var expressWs = expressWs(express()); | |
var app = expressWs.app; | |
app.use(express.static('public')); | |
var aWss = expressWs.getWss('/'); | |
app.ws('/', function(ws, req) { | |
console.log('Socket Connected'); | |
ws.onmessage = function(msg) { | |
console.log(msg.data); | |
aWss.clients.forEach(function (client) { | |
client.send(msg.data); | |
}); | |
}; | |
}); | |
app.listen(3444); |
V0 uses the syntax in the OP's gist. V1 does not support this, so you'll have to use another approach, such as @freebeans'.
Reason being, V0 used a separate WSS for each route, and V1 does not. The parameter used to specify which WSS to return.
This change actually contributed to the major version change.
More info from dev here: HenningM/express-ws#16
GJ!
get
I create a fork to enable fetching clients from a route like old getWss(route)
If anyone needs this feature check examples/url-filter-broadcast.js
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be aware
getWss()
doesn't take any arguments, it just so happens to not error out.You can't distinguish the connected clients between different routes without some hacks.
If anyone needs to broadcast to clients connected to a specific path, I suggest this:
Basically you're setting a flag on the ws instance inside the path handler and searching for it later.