Skip to content

Commit ad920e4

Browse files
feat: allow excluding all sockets in a room (#92)
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
1 parent 1a69c41 commit ad920e4

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ function Emitter(redis, prefix, nsp){
7575

7676
this._rooms = [];
7777
this._flags = {};
78+
this._except = [];
7879
}
7980

8081
/**
@@ -104,6 +105,14 @@ Emitter.prototype.to = function(room){
104105
return this;
105106
};
106107

108+
Emitter.prototype.except = function(room) {
109+
if (!~this._except.indexOf(room)) {
110+
debug('except %s', room);
111+
this._except.push(room);
112+
}
113+
return this;
114+
};
115+
107116
/**
108117
* Return a new emitter for the given namespace.
109118
*
@@ -127,7 +136,8 @@ Emitter.prototype.emit = function(){
127136

128137
var opts = {
129138
rooms: this._rooms,
130-
flags: this._flags
139+
flags: this._flags,
140+
except: this._except
131141
};
132142

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

145156
return this;
146157
};

test/index.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,5 +214,46 @@ describe('emitter', function() {
214214
});
215215
});
216216
});
217+
218+
it('should be able to exclude a socket by id', function(done) {
219+
var pub = redis.createClient();
220+
var sub = redis.createClient(null, null, {return_buffers: true});
221+
srv = http();
222+
var sio = io(srv, {adapter: redisAdapter({pubClient: pub, subClient: sub})});
223+
224+
var firstId = false;
225+
srv.listen(function() {
226+
sio.on('connection', function(socket) {
227+
if (firstId === false) {
228+
firstId = socket.id;
229+
}
230+
});
231+
});
232+
233+
var a = client(srv, { forceNew: true });
234+
var b;
235+
a.on('connect', function() {
236+
b = client(srv, { forceNew: true });
237+
b.on('connect', function() {
238+
239+
var calls = 0;
240+
a.on('except event', function() {
241+
calls++;
242+
expect().fail();
243+
});
244+
b.on('except event', function() {
245+
calls++;
246+
setTimeout(function() {
247+
expect(calls).to.be(1);
248+
done();
249+
}, 1);
250+
});
251+
252+
var emitter = ioe({ host: 'localhost', port: '6379' });
253+
emitter.except(firstId).emit('except event');
254+
255+
});
256+
});
257+
});
217258
});
218259
});

0 commit comments

Comments
 (0)