UNPKG

9.04 kBJavaScriptView Raw
1
2/**
3 * Module dependencies.
4 */
5
6var Emitter = require('events').EventEmitter;
7var parser = require('socket.io-parser');
8var url = require('url');
9var debug = require('debug')('socket.io:socket');
10var hasBin = require('has-binary');
11
12/**
13 * Module exports.
14 */
15
16module.exports = exports = Socket;
17
18/**
19 * Blacklisted events.
20 *
21 * @api public
22 */
23
24exports.events = [
25 'error',
26 'connect',
27 'disconnect',
28 'newListener',
29 'removeListener'
30];
31
32/**
33 * Flags.
34 *
35 * @api private
36 */
37
38var flags = [
39 'json',
40 'volatile',
41 'broadcast'
42];
43
44/**
45 * `EventEmitter#emit` reference.
46 */
47
48var emit = Emitter.prototype.emit;
49
50/**
51 * Interface to a `Client` for a given `Namespace`.
52 *
53 * @param {Namespace} nsp
54 * @param {Client} client
55 * @api public
56 */
57
58function Socket(nsp, client){
59 this.nsp = nsp;
60 this.server = nsp.server;
61 this.adapter = this.nsp.adapter;
62 this.id = nsp.name + '#' + client.id;
63 this.client = client;
64 this.conn = client.conn;
65 this.rooms = {};
66 this.acks = {};
67 this.connected = true;
68 this.disconnected = false;
69 this.handshake = this.buildHandshake();
70}
71
72/**
73 * Inherits from `EventEmitter`.
74 */
75
76Socket.prototype.__proto__ = Emitter.prototype;
77
78/**
79 * Apply flags from `Socket`.
80 */
81
82flags.forEach(function(flag){
83 Socket.prototype.__defineGetter__(flag, function(){
84 this.flags = this.flags || {};
85 this.flags[flag] = true;
86 return this;
87 });
88});
89
90/**
91 * `request` engine.io shortcut.
92 *
93 * @api public
94 */
95
96Socket.prototype.__defineGetter__('request', function(){
97 return this.conn.request;
98});
99
100/**
101 * Builds the `handshake` BC object
102 *
103 * @api private
104 */
105
106Socket.prototype.buildHandshake = function(){
107 return {
108 headers: this.request.headers,
109 time: (new Date) + '',
110 address: this.conn.remoteAddress,
111 xdomain: !!this.request.headers.origin,
112 secure: !!this.request.connection.encrypted,
113 issued: +(new Date),
114 url: this.request.url,
115 query: url.parse(this.request.url, true).query || {}
116 };
117};
118
119/**
120 * Emits to this client.
121 *
122 * @return {Socket} self
123 * @api public
124 */
125
126Socket.prototype.emit = function(ev){
127 if (~exports.events.indexOf(ev)) {
128 emit.apply(this, arguments);
129 } else {
130 var args = Array.prototype.slice.call(arguments);
131 var packet = {};
132 packet.type = hasBin(args) ? parser.BINARY_EVENT : parser.EVENT;
133 packet.data = args;
134 var flags = this.flags || {};
135
136 // access last argument to see if it's an ACK callback
137 if ('function' == typeof args[args.length - 1]) {
138 if (this._rooms || flags.broadcast) {
139 throw new Error('Callbacks are not supported when broadcasting');
140 }
141
142 debug('emitting packet with ack id %d', this.nsp.ids);
143 this.acks[this.nsp.ids] = args.pop();
144 packet.id = this.nsp.ids++;
145 }
146
147 if (this._rooms || flags.broadcast) {
148 this.adapter.broadcast(packet, {
149 except: [this.id],
150 rooms: this._rooms,
151 flags: flags
152 });
153 } else {
154 // dispatch packet
155 this.packet(packet, {
156 volatile: flags.volatile,
157 compress: flags.compress
158 });
159 }
160
161 // reset flags
162 delete this._rooms;
163 delete this.flags;
164 }
165 return this;
166};
167
168/**
169 * Targets a room when broadcasting.
170 *
171 * @param {String} name
172 * @return {Socket} self
173 * @api public
174 */
175
176Socket.prototype.to =
177Socket.prototype.in = function(name){
178 this._rooms = this._rooms || [];
179 if (!~this._rooms.indexOf(name)) this._rooms.push(name);
180 return this;
181};
182
183/**
184 * Sends a `message` event.
185 *
186 * @return {Socket} self
187 * @api public
188 */
189
190Socket.prototype.send =
191Socket.prototype.write = function(){
192 var args = Array.prototype.slice.call(arguments);
193 args.unshift('message');
194 this.emit.apply(this, args);
195 return this;
196};
197
198/**
199 * Writes a packet.
200 *
201 * @param {Object} packet object
202 * @param {Object} opts options
203 * @api private
204 */
205
206Socket.prototype.packet = function(packet, opts){
207 packet.nsp = this.nsp.name;
208 opts = opts || {};
209 opts.compress = false !== opts.compress;
210 this.client.packet(packet, opts);
211};
212
213/**
214 * Joins a room.
215 *
216 * @param {String} room
217 * @param {Function} fn optional, callback
218 * @return {Socket} self
219 * @api private
220 */
221
222Socket.prototype.join = function(room, fn){
223 debug('joining room %s', room);
224 var self = this;
225 if (this.rooms.hasOwnProperty(room)) {
226 fn && fn(null);
227 return this;
228 }
229 this.adapter.add(this.id, room, function(err){
230 if (err) return fn && fn(err);
231 debug('joined room %s', room);
232 self.rooms[room] = room;
233 fn && fn(null);
234 });
235 return this;
236};
237
238/**
239 * Leaves a room.
240 *
241 * @param {String} room
242 * @param {Function} fn optional, callback
243 * @return {Socket} self
244 * @api private
245 */
246
247Socket.prototype.leave = function(room, fn){
248 debug('leave room %s', room);
249 var self = this;
250 this.adapter.del(this.id, room, function(err){
251 if (err) return fn && fn(err);
252 debug('left room %s', room);
253 delete self.rooms[room];
254 fn && fn(null);
255 });
256 return this;
257};
258
259/**
260 * Leave all rooms.
261 *
262 * @api private
263 */
264
265Socket.prototype.leaveAll = function(){
266 this.adapter.delAll(this.id);
267 this.rooms = {};
268};
269
270/**
271 * Called by `Namespace` upon succesful
272 * middleware execution (ie: authorization).
273 *
274 * @api private
275 */
276
277Socket.prototype.onconnect = function(){
278 debug('socket connected - writing packet');
279 this.nsp.connected[this.id] = this;
280 this.join(this.id);
281 this.packet({ type: parser.CONNECT });
282};
283
284/**
285 * Called with each packet. Called by `Client`.
286 *
287 * @param {Object} packet
288 * @api private
289 */
290
291Socket.prototype.onpacket = function(packet){
292 debug('got packet %j', packet);
293 switch (packet.type) {
294 case parser.EVENT:
295 this.onevent(packet);
296 break;
297
298 case parser.BINARY_EVENT:
299 this.onevent(packet);
300 break;
301
302 case parser.ACK:
303 this.onack(packet);
304 break;
305
306 case parser.BINARY_ACK:
307 this.onack(packet);
308 break;
309
310 case parser.DISCONNECT:
311 this.ondisconnect();
312 break;
313
314 case parser.ERROR:
315 this.emit('error', packet.data);
316 }
317};
318
319/**
320 * Called upon event packet.
321 *
322 * @param {Object} packet object
323 * @api private
324 */
325
326Socket.prototype.onevent = function(packet){
327 var args = packet.data || [];
328 debug('emitting event %j', args);
329
330 if (null != packet.id) {
331 debug('attaching ack callback to event');
332 args.push(this.ack(packet.id));
333 }
334
335 emit.apply(this, args);
336};
337
338/**
339 * Produces an ack callback to emit with an event.
340 *
341 * @param {Number} id packet id
342 * @api private
343 */
344
345Socket.prototype.ack = function(id){
346 var self = this;
347 var sent = false;
348 return function(){
349 // prevent double callbacks
350 if (sent) return;
351 var args = Array.prototype.slice.call(arguments);
352 debug('sending ack %j', args);
353
354 var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
355 self.packet({
356 id: id,
357 type: type,
358 data: args
359 });
360
361 sent = true;
362 };
363};
364
365/**
366 * Called upon ack packet.
367 *
368 * @api private
369 */
370
371Socket.prototype.onack = function(packet){
372 var ack = this.acks[packet.id];
373 if ('function' == typeof ack) {
374 debug('calling ack %s with %j', packet.id, packet.data);
375 ack.apply(this, packet.data);
376 delete this.acks[packet.id];
377 } else {
378 debug('bad ack %s', packet.id);
379 }
380};
381
382/**
383 * Called upon client disconnect packet.
384 *
385 * @api private
386 */
387
388Socket.prototype.ondisconnect = function(){
389 debug('got disconnect packet');
390 this.onclose('client namespace disconnect');
391};
392
393/**
394 * Handles a client error.
395 *
396 * @api private
397 */
398
399Socket.prototype.onerror = function(err){
400 if (this.listeners('error').length) {
401 this.emit('error', err);
402 } else {
403 console.error('Missing error handler on `socket`.');
404 console.error(err.stack);
405 }
406};
407
408/**
409 * Called upon closing. Called by `Client`.
410 *
411 * @param {String} reason
412 * @throw {Error} optional error object
413 * @api private
414 */
415
416Socket.prototype.onclose = function(reason){
417 if (!this.connected) return this;
418 debug('closing socket - reason %s', reason);
419 this.leaveAll();
420 this.nsp.remove(this);
421 this.client.remove(this);
422 this.connected = false;
423 this.disconnected = true;
424 delete this.nsp.connected[this.id];
425 this.emit('disconnect', reason);
426};
427
428/**
429 * Produces an `error` packet.
430 *
431 * @param {Object} err error object
432 * @api private
433 */
434
435Socket.prototype.error = function(err){
436 this.packet({ type: parser.ERROR, data: err });
437};
438
439/**
440 * Disconnects this client.
441 *
442 * @param {Boolean} close if `true`, closes the underlying connection
443 * @return {Socket} self
444 * @api public
445 */
446
447Socket.prototype.disconnect = function(close){
448 if (!this.connected) return this;
449 if (close) {
450 this.client.disconnect();
451 } else {
452 this.packet({ type: parser.DISCONNECT });
453 this.onclose('server namespace disconnect');
454 }
455 return this;
456};
457
458/**
459 * Sets the compress flag.
460 *
461 * @param {Boolean} compress if `true`, compresses the sending data
462 * @return {Socket} self
463 * @api public
464 */
465
466Socket.prototype.compress = function(compress){
467 this.flags = this.flags || {};
468 this.flags.compress = compress;
469 return this;
470};