Skip to content

Instantly share code, notes, and snippets.

@hugosp
Created April 4, 2016 22:37
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hugosp/5eeb2a375157625e21d33d75d10574df to your computer and use it in GitHub Desktop.
Save hugosp/5eeb2a375157625e21d33d75d10574df to your computer and use it in GitHub Desktop.
Minimal express-ws broadcast to all clients
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);
@aatina
Copy link

aatina commented Apr 11, 2018

Thanks for this! I was stuck on it too long 👍

@dylanbaxter
Copy link

+1

@expertup
Copy link

+1

@claudiosousa
Copy link

+1

@freebeans
Copy link

freebeans commented Oct 25, 2019

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.

@adalovebass
Copy link

adalovebass commented Dec 14, 2019

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

@howmuch515
Copy link

GJ!

@vsTianhao
Copy link

get

@MiopeCiclope
Copy link

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