Skip to content

Commit

Permalink
feat: allow excluding all sockets in a room (#92)
Browse files Browse the repository at this point in the history
Syntax:

```js
io.to("room1").except("room2").emit(/* ... */);
```

Related: https://socket.io/docs/v4/migrating-from-3-x-to-4-0/#Allow-excluding-specific-rooms-when-broadcasting
  • Loading branch information
sebamarynissen authored Mar 17, 2021
1 parent 1a69c41 commit ad920e4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ function Emitter(redis, prefix, nsp){

this._rooms = [];
this._flags = {};
this._except = [];
}

/**
Expand Down Expand Up @@ -104,6 +105,14 @@ Emitter.prototype.to = function(room){
return this;
};

Emitter.prototype.except = function(room) {
if (!~this._except.indexOf(room)) {
debug('except %s', room);
this._except.push(room);
}
return this;
};

/**
* Return a new emitter for the given namespace.
*
Expand All @@ -127,7 +136,8 @@ Emitter.prototype.emit = function(){

var opts = {
rooms: this._rooms,
flags: this._flags
flags: this._flags,
except: this._except
};

var msg = msgpack.encode([uid, packet, opts]);
Expand All @@ -141,6 +151,7 @@ Emitter.prototype.emit = function(){
// reset state
this._rooms = [];
this._flags = {};
this._except = [];

return this;
};
41 changes: 41 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,5 +214,46 @@ describe('emitter', function() {
});
});
});

it('should be able to exclude a socket by id', function(done) {
var pub = redis.createClient();
var sub = redis.createClient(null, null, {return_buffers: true});
srv = http();
var sio = io(srv, {adapter: redisAdapter({pubClient: pub, subClient: sub})});

var firstId = false;
srv.listen(function() {
sio.on('connection', function(socket) {
if (firstId === false) {
firstId = socket.id;
}
});
});

var a = client(srv, { forceNew: true });
var b;
a.on('connect', function() {
b = client(srv, { forceNew: true });
b.on('connect', function() {

var calls = 0;
a.on('except event', function() {
calls++;
expect().fail();
});
b.on('except event', function() {
calls++;
setTimeout(function() {
expect(calls).to.be(1);
done();
}, 1);
});

var emitter = ioe({ host: 'localhost', port: '6379' });
emitter.except(firstId).emit('except event');

});
});
});
});
});

0 comments on commit ad920e4

Please sign in to comment.