Skip to content

Commit 43d9a4b

Browse files
[feature] Add a 'disconnecting' event to access to socket.rooms upon disconnection (#2332)
1 parent df91617 commit 43d9a4b

3 files changed

Lines changed: 45 additions & 1 deletion

File tree

Readme.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,24 @@ server.listen(3000);
402402

403403
Disconnects this client. If value of close is `true`, closes the underlying connection.
404404
Otherwise, it just disconnects the namespace.
405-
405+
406+
#### Events
407+
408+
- `disconnect`
409+
- Fired upon disconnection.
410+
- **Arguments**
411+
- `String`: the reason of the disconnection (either client or server-side)
412+
- `error`
413+
- Fired when an error occurs.
414+
- **Arguments**
415+
- `Object`: error data
416+
- `disconnecting`
417+
- Fired when the client is going to be disconnected (but hasn't left its `rooms` yet).
418+
- **Arguments**
419+
- `String`: the reason of the disconnection (either client or server-side)
420+
421+
These are reserved events (along with `connect`, `newListener` and `removeListener`) which cannot be used as event names.
422+
406423

407424
### Client
408425

lib/socket.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ exports.events = [
2525
'error',
2626
'connect',
2727
'disconnect',
28+
'disconnecting',
2829
'newListener',
2930
'removeListener'
3031
];
@@ -428,6 +429,7 @@ Socket.prototype.onerror = function(err){
428429
Socket.prototype.onclose = function(reason){
429430
if (!this.connected) return this;
430431
debug('closing socket - reason %s', reason);
432+
this.emit('disconnecting', reason);
431433
this.leaveAll();
432434
this.nsp.remove(this);
433435
this.client.remove(this);

test/socket.io.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,31 @@ describe('socket.io', function(){
644644
});
645645
});
646646

647+
it('should fire a `disconnecting` event just before leaving all rooms', function(done){
648+
var srv = http();
649+
var sio = io(srv);
650+
srv.listen(function(){
651+
var socket = client(srv);
652+
653+
sio.on('connection', function(s){
654+
s.join('a', function(){
655+
s.disconnect();
656+
});
657+
658+
var total = 2;
659+
s.on('disconnecting', function(reason){
660+
expect(Object.keys(s.rooms)).to.eql([s.id, 'a']);
661+
total--;
662+
});
663+
664+
s.on('disconnect', function(reason){
665+
expect(Object.keys(s.rooms)).to.eql([]);
666+
--total || done();
667+
});
668+
});
669+
});
670+
});
671+
647672
it('should return error connecting to non-existent namespace', function(done){
648673
var srv = http();
649674
var sio = io(srv);

0 commit comments

Comments
 (0)