Skip to content

Send message to all sockets except some when running on multiple nodes #3629

Closed
@sebamarynissen

Description

@sebamarynissen

You want to:

  • report a bug
  • request a feature

Current behaviour

When running on multiple nodes with socket.io-redis there is no way to emit a message to all sockets in a namespace except a specific socket if the socket you want to omit is not on that node.

Currently you can only do

socket.broadcast.to('room').emit('hi', 'all');

which won't work on multiple nodes because the socket is not available to all nodes.

Expected behaviour

It would be nice to have a way to broadcast to all sockets except a specific one a node that does not contain the socket we want to omit. I therefore propose to add a method .except(id) that can be used as

io.to('room').except('id').emit('hi', 'all');

Setup

  • OS: any
  • browser: any
  • socket.io version: any

Implementation

I would be happy to file a PR for this if this functionality would be accepted. The implementation could looke like this:

// In namespace.js
function Namespace(server, name){
  this.name = name;
  this.server = server;
  this.sockets = {};
  this.connected = {};
  this.fns = [];
  this.ids = 0;
  this.rooms = [];
  this.flags = {};
  this.omit = [];
  this.initAdapter();
}

Namespace.prototype.except = function(id){
  this.omit.push(id);
  return this;
};

Namespace.prototype.emit = function(ev){

  // ...

  var rooms = this.rooms.slice(0);
  var flags = Object.assign({}, this.flags);
  var except = this.omit.slice(0);

  // reset flags
  this.rooms = [];
  this.flags = {};
  this.omit = [];

  this.adapter.broadcast(packet, {
    rooms: rooms,
    flags: flags,
    except: except
  });

  return this;
};

As far as I know this works with socket.io-redis out of the box. See also socketio/socket.io-redis-emitter#87 for a similar feature for socket.io-emitter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions