-
-
Save hugosp/5eeb2a375157625e21d33d75d10574df to your computer and use it in GitHub Desktop.
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); |
+1
+1
+1
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:
app.ws('/', function(ws, req) {
console.log('Socket Connected');
ws.route = '/'; /* <- Your path */
ws.onmessage = function(msg) {
console.log(msg.data);
Array.from(
wss.getWss().clients
).filter((sock)=>{
return sock.route == '/' /* <- Your path */
}).forEach(function (client) {
client.send(msg.data);
});
};
});
Basically you're setting a flag on the ws instance inside the path handler and searching for it later.
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
Thanks for this! I was stuck on it too long 👍