forked from socketio/socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.js
122 lines (105 loc) · 2.36 KB
/
adapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/**
* Module dependencies.
*/
var Emitter = require('events').EventEmitter;
/**
* Module exports.
*/
module.exports = Adapter;
/**
* Memory adapter constructor.
*
* @param {Namespace} nsp
* @api public
*/
function Adapter(nsp){
this.nsp = nsp;
this.rooms = {};
this.sids = {};
}
/**
* Inherits from `EventEmitter`.
*/
Adapter.prototype.__proto__ = Emitter.prototype;
/**
* Adds a socket from a room.
*
* @param {String} socket id
* @param {String} room name
* @param {Function} callback
* @api public
*/
Adapter.prototype.add = function(id, room, fn){
this.sids[id] = this.sids[id] || {};
this.sids[id][room] = true;
this.rooms[room] = this.rooms[room] || [];
this.rooms[room][id] = true;
if (fn) process.nextTick(fn.bind(null, null));
};
/**
* Removes a socket from a room.
*
* @param {String} socket id
* @param {String} room name
* @param {Function} callback
* @api public
*/
Adapter.prototype.del = function(id, room, fn){
this.sids[id] = this.sids[id] || {};
this.rooms[room] = this.rooms[room] || {};
delete this.sids[id][room];
delete this.rooms[room][id];
if (fn) process.nextTick(fn.bind(null, null));
};
/**
* Removes a socket from all rooms it's joined.
*
* @param {String} socket id
* @api public
*/
Adapter.prototype.delAll = function(id, fn){
var rooms = this.sids[id];
if (rooms) {
for (var room in rooms) {
delete this.rooms[room][id];
}
}
delete this.sids[id];
};
/**
* Broadcasts a packet.
*
* Options:
* - `flags` {Object} flags for this packet
* - `except` {Array} sids that should be excluded
* - `rooms` {Array} list of rooms to broadcast to
*
* @param {Object} packet object
* @api public
*/
Adapter.prototype.broadcast = function(packet, opts){
var rooms = opts.rooms || [];
var except = opts.except || [];
var ids = {};
var socket;
if (rooms.length) {
for (var i = 0; i < rooms.length; i++) {
var room = this.rooms[rooms[i]];
if (!room) continue;
for (var id in room) {
if (ids[id] || ~except.indexOf(id)) continue;
socket = this.nsp.connected[id];
if (socket) {
socket.packet(packet);
ids[id] = true;
}
}
}
} else {
for (var id in this.sids) {
if (~except.indexOf(id)) continue;
socket = this.nsp.connected[id];
if (socket) socket.packet(packet);
}
}
};