Skip to content

Replace 'express-ws' #1

Description

@Albin-Rohde

The npm package express-ws does not seem to support broadcasting to a clients on a specific route or context.

For example Imagine Client A creates a game on the ws-route ../game/lobby/<unique_key_1>.
Client B joins the game via a private link ../game/<unique_key_1>.
We now want to broadcast to everyone connected to ../game/<unique_key_1>/join that a new client has joined, and thus update the UI on both ends. Telling them how many players are in the game.

The issue right now is that broadcasting on a specific route is not possible in express-ws. I.e if we where to broadcast the new Game state to all clients; A Client C would also receive that message. The message would contain data such as <unique_key_1>.

Client C should not have access to such information, but now has, and can now hijack the game, and join via ../game/<unique_key_1>/join. Even though Client C never received an invite.

This issue was discussed here: https://gist.github.com/hugosp/5eeb2a375157625e21d33d75d10574df

OP sugest a solution:

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

But as highlited in the issue ticket, getWss() does not support path/route as argument
https://github.com/HenningM/express-ws/blob/master/src/index.js#L80

A possible solution was discussed as follows:

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

After investigation however; it does not seem like ws has any property route. Which renders this solution invalid for express-ws@latest

This issue was further discussed in a PR a while back
HenningM/express-ws#122

But has as of yet not been merged. The owner of the PR has a fork for the project, which might be worth looking into.
https://github.com/aral/express-ws

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions