PageRenderTime 46ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/platforms/node/node_modules/socket.io/lib/socket.js

https://github.com/paramarco/visible
JavaScript | 429 lines | 220 code | 64 blank | 145 comment | 35 complexity | 486a51f0aabe5ca8d95093a15adc43b4 MD5 | raw file
Possible License(s): MIT, 0BSD, Apache-2.0, GPL-2.0, BSD-3-Clause
  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 hasBin = require('has-binary-data');
  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. 'newListener',
  23. 'removeListener'
  24. ];
  25. /**
  26. * Flags.
  27. *
  28. * @api private
  29. */
  30. var flags = [
  31. 'json',
  32. 'volatile',
  33. 'broadcast'
  34. ];
  35. /**
  36. * `EventEmitter#emit` reference.
  37. */
  38. var emit = Emitter.prototype.emit;
  39. /**
  40. * Interface to a `Client` for a given `Namespace`.
  41. *
  42. * @param {Namespace} nsp
  43. * @param {Client} client
  44. * @api public
  45. */
  46. function Socket(nsp, client){
  47. this.nsp = nsp;
  48. this.server = nsp.server;
  49. this.adapter = this.nsp.adapter;
  50. this.id = client.id;
  51. this.request = client.request;
  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();
  59. }
  60. /**
  61. * Inherits from `EventEmitter`.
  62. */
  63. Socket.prototype.__proto__ = Emitter.prototype;
  64. /**
  65. * Apply flags from `Socket`.
  66. */
  67. flags.forEach(function(flag){
  68. Socket.prototype.__defineGetter__(flag, function(){
  69. this.flags = this.flags || {};
  70. this.flags[flag] = true;
  71. return this;
  72. });
  73. });
  74. /**
  75. * `request` engine.io shorcut.
  76. *
  77. * @api public
  78. */
  79. Socket.prototype.__defineGetter__('request', function(){
  80. return this.conn.request;
  81. });
  82. /**
  83. * Builds the `handshake` BC object
  84. *
  85. * @api private
  86. */
  87. Socket.prototype.buildHandshake = function(){
  88. return {
  89. headers: this.request.headers,
  90. time: (new Date) + '',
  91. address: this.request.connection.address(),
  92. xdomain: !!this.request.headers.origin,
  93. secure: !!this.request.connection.encrypted,
  94. issued: +(new Date),
  95. url: this.request.url,
  96. query: url.parse(this.request.url, true).query || {}
  97. };
  98. };
  99. /**
  100. * Emits to this client.
  101. *
  102. * @return {Socket} self
  103. * @api public
  104. */
  105. Socket.prototype.emit = function(ev){
  106. if (~exports.events.indexOf(ev)) {
  107. emit.apply(this, arguments);
  108. } else {
  109. var args = Array.prototype.slice.call(arguments);
  110. var packet = {};
  111. packet.type = hasBin(args) ? parser.BINARY_EVENT : parser.EVENT;
  112. packet.data = args;
  113. // access last argument to see if it's an ACK callback
  114. if ('function' == typeof args[args.length - 1]) {
  115. if (this._rooms || (this.flags && this.flags.broadcast)) {
  116. throw new Error('Callbacks are not supported when broadcasting');
  117. }
  118. debug('emitting packet with ack id %d', this.nsp.ids);
  119. this.acks[this.nsp.ids] = args.pop();
  120. packet.id = this.nsp.ids++;
  121. }
  122. if (this._rooms || (this.flags && this.flags.broadcast)) {
  123. this.adapter.broadcast(packet, {
  124. except: [this.id],
  125. rooms: this._rooms,
  126. flags: this.flags
  127. });
  128. } else {
  129. // dispatch packet
  130. this.packet(packet);
  131. }
  132. // reset flags
  133. delete this._rooms;
  134. delete this.flags;
  135. }
  136. return this;
  137. };
  138. /**
  139. * Targets a room when broadcasting.
  140. *
  141. * @param {String} name
  142. * @return {Socket} self
  143. * @api public
  144. */
  145. Socket.prototype.to =
  146. Socket.prototype.in = function(name){
  147. this._rooms = this._rooms || [];
  148. if (!~this._rooms.indexOf(name)) this._rooms.push(name);
  149. return this;
  150. };
  151. /**
  152. * Sends a `message` event.
  153. *
  154. * @return {Socket} self
  155. * @api public
  156. */
  157. Socket.prototype.send =
  158. Socket.prototype.write = function(){
  159. var args = Array.prototype.slice.call(arguments);
  160. args.unshift('message');
  161. this.emit.apply(this, args);
  162. return this;
  163. };
  164. /**
  165. * Writes a packet.
  166. *
  167. * @param {Object} packet object
  168. * @api private
  169. */
  170. Socket.prototype.packet = function(packet, preEncoded){
  171. packet.nsp = this.nsp.name;
  172. var volatile = this.flags && this.flags.volatile;
  173. this.client.packet(packet, preEncoded, volatile);
  174. };
  175. /**
  176. * Joins a room.
  177. *
  178. * @param {String} room
  179. * @param {Function} optional, callback
  180. * @return {Socket} self
  181. * @api private
  182. */
  183. Socket.prototype.join = function(room, fn){
  184. debug('joining room %s', room);
  185. var self = this;
  186. if (~this.rooms.indexOf(room)) return this;
  187. this.adapter.add(this.id, room, function(err){
  188. if (err) return fn && fn(err);
  189. debug('joined room %s', room);
  190. self.rooms.push(room);
  191. fn && fn(null);
  192. });
  193. return this;
  194. };
  195. /**
  196. * Leaves a room.
  197. *
  198. * @param {String} room
  199. * @param {Function} optional, callback
  200. * @return {Socket} self
  201. * @api private
  202. */
  203. Socket.prototype.leave = function(room, fn){
  204. debug('leave room %s', room);
  205. var self = this;
  206. this.adapter.del(this.id, room, function(err){
  207. if (err) return fn && fn(err);
  208. debug('left room %s', room);
  209. self.rooms.splice(self.rooms.indexOf(room, 1));
  210. fn && fn(null);
  211. });
  212. return this;
  213. };
  214. /**
  215. * Leave all rooms.
  216. *
  217. * @api private
  218. */
  219. Socket.prototype.leaveAll = function(){
  220. this.adapter.delAll(this.id);
  221. };
  222. /**
  223. * Called by `Namespace` upon succesful
  224. * middleware execution (ie: authorization).
  225. *
  226. * @api private
  227. */
  228. Socket.prototype.onconnect = function(){
  229. debug('socket connected - writing packet');
  230. this.join(this.id);
  231. this.packet({ type: parser.CONNECT });
  232. this.nsp.connected[this.id] = this;
  233. };
  234. /**
  235. * Called with each packet. Called by `Client`.
  236. *
  237. * @param {Object} packet
  238. * @api private
  239. */
  240. Socket.prototype.onpacket = function(packet){
  241. debug('got packet %j', packet);
  242. switch (packet.type) {
  243. case parser.EVENT:
  244. this.onevent(packet);
  245. break;
  246. case parser.BINARY_EVENT:
  247. this.onevent(packet);
  248. break;
  249. case parser.ACK:
  250. this.onack(packet);
  251. break;
  252. case parser.BINARY_ACK:
  253. this.onack(packet);
  254. break;
  255. case parser.DISCONNECT:
  256. this.ondisconnect();
  257. break;
  258. case parser.ERROR:
  259. this.emit('error', packet.data);
  260. }
  261. };
  262. /**
  263. * Called upon event packet.
  264. *
  265. * @param {Object} packet object
  266. * @api private
  267. */
  268. Socket.prototype.onevent = function(packet){
  269. var args = packet.data || [];
  270. debug('emitting event %j', args);
  271. if (null != packet.id) {
  272. debug('attaching ack callback to event');
  273. args.push(this.ack(packet.id));
  274. }
  275. emit.apply(this, args);
  276. };
  277. /**
  278. * Produces an ack callback to emit with an event.
  279. *
  280. * @param {Number} packet id
  281. * @api private
  282. */
  283. Socket.prototype.ack = function(id){
  284. var self = this;
  285. var sent = false;
  286. return function(){
  287. // prevent double callbacks
  288. if (sent) return;
  289. var args = Array.prototype.slice.call(arguments);
  290. debug('sending ack %j', args);
  291. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  292. self.packet({
  293. id: id,
  294. type: type,
  295. data: args
  296. });
  297. };
  298. };
  299. /**
  300. * Called upon ack packet.
  301. *
  302. * @api private
  303. */
  304. Socket.prototype.onack = function(packet){
  305. var ack = this.acks[packet.id];
  306. if ('function' == typeof ack) {
  307. debug('calling ack %s with %j', packet.id, packet.data);
  308. ack.apply(this, packet.data);
  309. delete this.acks[packet.id];
  310. } else {
  311. debug('bad ack %s', packet.id);
  312. }
  313. };
  314. /**
  315. * Called upon client disconnect packet.
  316. *
  317. * @api private
  318. */
  319. Socket.prototype.ondisconnect = function(){
  320. debug('got disconnect packet');
  321. this.onclose('client namespace disconnect');
  322. };
  323. /**
  324. * Called upon closing. Called by `Client`.
  325. *
  326. * @param {String} reason
  327. * @api private
  328. */
  329. Socket.prototype.onclose = function(reason){
  330. if (!this.connected) return this;
  331. debug('closing socket - reason %s', reason);
  332. this.leaveAll();
  333. this.nsp.remove(this);
  334. this.client.remove(this);
  335. this.connected = false;
  336. this.disconnected = true;
  337. delete this.nsp.connected[this.id];
  338. this.emit('disconnect', reason);
  339. };
  340. /**
  341. * Produces an `error` packet.
  342. *
  343. * @param {Object} error object
  344. * @api private
  345. */
  346. Socket.prototype.error = function(err){
  347. this.packet({ type: parser.ERROR, data: err });
  348. };
  349. /**
  350. * Disconnects this client.
  351. *
  352. * @param {Boolean} if `true`, closes the underlying connection
  353. * @return {Socket} self
  354. * @api public
  355. */
  356. Socket.prototype.disconnect = function(close){
  357. if (!this.connected) return this;
  358. if (close) {
  359. this.client.disconnect();
  360. } else {
  361. this.packet({ type: parser.DISCONNECT });
  362. this.onclose('server namespace disconnect');
  363. }
  364. return this;
  365. };