You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

430 lines
8.1 KiB

  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.conn.remoteAddress,
  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. this.rooms = [];
  222. };
  223. /**
  224. * Called by `Namespace` upon succesful
  225. * middleware execution (ie: authorization).
  226. *
  227. * @api private
  228. */
  229. Socket.prototype.onconnect = function(){
  230. debug('socket connected - writing packet');
  231. this.join(this.id);
  232. this.packet({ type: parser.CONNECT });
  233. this.nsp.connected[this.id] = this;
  234. };
  235. /**
  236. * Called with each packet. Called by `Client`.
  237. *
  238. * @param {Object} packet
  239. * @api private
  240. */
  241. Socket.prototype.onpacket = function(packet){
  242. debug('got packet %j', packet);
  243. switch (packet.type) {
  244. case parser.EVENT:
  245. this.onevent(packet);
  246. break;
  247. case parser.BINARY_EVENT:
  248. this.onevent(packet);
  249. break;
  250. case parser.ACK:
  251. this.onack(packet);
  252. break;
  253. case parser.BINARY_ACK:
  254. this.onack(packet);
  255. break;
  256. case parser.DISCONNECT:
  257. this.ondisconnect();
  258. break;
  259. case parser.ERROR:
  260. this.emit('error', packet.data);
  261. }
  262. };
  263. /**
  264. * Called upon event packet.
  265. *
  266. * @param {Object} packet object
  267. * @api private
  268. */
  269. Socket.prototype.onevent = function(packet){
  270. var args = packet.data || [];
  271. debug('emitting event %j', args);
  272. if (null != packet.id) {
  273. debug('attaching ack callback to event');
  274. args.push(this.ack(packet.id));
  275. }
  276. emit.apply(this, args);
  277. };
  278. /**
  279. * Produces an ack callback to emit with an event.
  280. *
  281. * @param {Number} packet id
  282. * @api private
  283. */
  284. Socket.prototype.ack = function(id){
  285. var self = this;
  286. var sent = false;
  287. return function(){
  288. // prevent double callbacks
  289. if (sent) return;
  290. var args = Array.prototype.slice.call(arguments);
  291. debug('sending ack %j', args);
  292. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  293. self.packet({
  294. id: id,
  295. type: type,
  296. data: args
  297. });
  298. };
  299. };
  300. /**
  301. * Called upon ack packet.
  302. *
  303. * @api private
  304. */
  305. Socket.prototype.onack = function(packet){
  306. var ack = this.acks[packet.id];
  307. if ('function' == typeof ack) {
  308. debug('calling ack %s with %j', packet.id, packet.data);
  309. ack.apply(this, packet.data);
  310. delete this.acks[packet.id];
  311. } else {
  312. debug('bad ack %s', packet.id);
  313. }
  314. };
  315. /**
  316. * Called upon client disconnect packet.
  317. *
  318. * @api private
  319. */
  320. Socket.prototype.ondisconnect = function(){
  321. debug('got disconnect packet');
  322. this.onclose('client namespace disconnect');
  323. };
  324. /**
  325. * Called upon closing. Called by `Client`.
  326. *
  327. * @param {String} reason
  328. * @api private
  329. */
  330. Socket.prototype.onclose = function(reason){
  331. if (!this.connected) return this;
  332. debug('closing socket - reason %s', reason);
  333. this.leaveAll();
  334. this.nsp.remove(this);
  335. this.client.remove(this);
  336. this.connected = false;
  337. this.disconnected = true;
  338. delete this.nsp.connected[this.id];
  339. this.emit('disconnect', reason);
  340. };
  341. /**
  342. * Produces an `error` packet.
  343. *
  344. * @param {Object} error object
  345. * @api private
  346. */
  347. Socket.prototype.error = function(err){
  348. this.packet({ type: parser.ERROR, data: err });
  349. };
  350. /**
  351. * Disconnects this client.
  352. *
  353. * @param {Boolean} if `true`, closes the underlying connection
  354. * @return {Socket} self
  355. * @api public
  356. */
  357. Socket.prototype.disconnect = function(close){
  358. if (!this.connected) return this;
  359. if (close) {
  360. this.client.disconnect();
  361. } else {
  362. this.packet({ type: parser.DISCONNECT });
  363. this.onclose('server namespace disconnect');
  364. }
  365. return this;
  366. };