socket.js 11 KB

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