socket.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import { PacketType } from "socket.io-parser";
  2. import { on } from "./on.js";
  3. import { Emitter, } from "@socket.io/component-emitter";
  4. /**
  5. * Internal events.
  6. * These events can't be emitted by the user.
  7. */
  8. const RESERVED_EVENTS = Object.freeze({
  9. connect: 1,
  10. connect_error: 1,
  11. disconnect: 1,
  12. disconnecting: 1,
  13. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  14. newListener: 1,
  15. removeListener: 1,
  16. });
  17. export class Socket extends Emitter {
  18. /**
  19. * `Socket` constructor.
  20. *
  21. * @public
  22. */
  23. constructor(io, nsp, opts) {
  24. super();
  25. this.connected = false;
  26. this.disconnected = true;
  27. this.receiveBuffer = [];
  28. this.sendBuffer = [];
  29. this.ids = 0;
  30. this.acks = {};
  31. this.flags = {};
  32. this.io = io;
  33. this.nsp = nsp;
  34. if (opts && opts.auth) {
  35. this.auth = opts.auth;
  36. }
  37. if (this.io._autoConnect)
  38. this.open();
  39. }
  40. /**
  41. * Subscribe to open, close and packet events
  42. *
  43. * @private
  44. */
  45. subEvents() {
  46. if (this.subs)
  47. return;
  48. const io = this.io;
  49. this.subs = [
  50. on(io, "open", this.onopen.bind(this)),
  51. on(io, "packet", this.onpacket.bind(this)),
  52. on(io, "error", this.onerror.bind(this)),
  53. on(io, "close", this.onclose.bind(this)),
  54. ];
  55. }
  56. /**
  57. * Whether the Socket will try to reconnect when its Manager connects or reconnects
  58. */
  59. get active() {
  60. return !!this.subs;
  61. }
  62. /**
  63. * "Opens" the socket.
  64. *
  65. * @public
  66. */
  67. connect() {
  68. if (this.connected)
  69. return this;
  70. this.subEvents();
  71. if (!this.io["_reconnecting"])
  72. this.io.open(); // ensure open
  73. if ("open" === this.io._readyState)
  74. this.onopen();
  75. return this;
  76. }
  77. /**
  78. * Alias for connect()
  79. */
  80. open() {
  81. return this.connect();
  82. }
  83. /**
  84. * Sends a `message` event.
  85. *
  86. * @return self
  87. * @public
  88. */
  89. send(...args) {
  90. args.unshift("message");
  91. this.emit.apply(this, args);
  92. return this;
  93. }
  94. /**
  95. * Override `emit`.
  96. * If the event is in `events`, it's emitted normally.
  97. *
  98. * @return self
  99. * @public
  100. */
  101. emit(ev, ...args) {
  102. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  103. throw new Error('"' + ev + '" is a reserved event name');
  104. }
  105. args.unshift(ev);
  106. const packet = {
  107. type: PacketType.EVENT,
  108. data: args,
  109. };
  110. packet.options = {};
  111. packet.options.compress = this.flags.compress !== false;
  112. // event ack callback
  113. if ("function" === typeof args[args.length - 1]) {
  114. const id = this.ids++;
  115. const ack = args.pop();
  116. this._registerAckCallback(id, ack);
  117. packet.id = id;
  118. }
  119. const isTransportWritable = this.io.engine &&
  120. this.io.engine.transport &&
  121. this.io.engine.transport.writable;
  122. const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);
  123. if (discardPacket) {
  124. }
  125. else if (this.connected) {
  126. this.packet(packet);
  127. }
  128. else {
  129. this.sendBuffer.push(packet);
  130. }
  131. this.flags = {};
  132. return this;
  133. }
  134. /**
  135. * @private
  136. */
  137. _registerAckCallback(id, ack) {
  138. const timeout = this.flags.timeout;
  139. if (timeout === undefined) {
  140. this.acks[id] = ack;
  141. return;
  142. }
  143. // @ts-ignore
  144. const timer = this.io.setTimeoutFn(() => {
  145. delete this.acks[id];
  146. for (let i = 0; i < this.sendBuffer.length; i++) {
  147. if (this.sendBuffer[i].id === id) {
  148. this.sendBuffer.splice(i, 1);
  149. }
  150. }
  151. ack.call(this, new Error("operation has timed out"));
  152. }, timeout);
  153. this.acks[id] = (...args) => {
  154. // @ts-ignore
  155. this.io.clearTimeoutFn(timer);
  156. ack.apply(this, [null, ...args]);
  157. };
  158. }
  159. /**
  160. * Sends a packet.
  161. *
  162. * @param packet
  163. * @private
  164. */
  165. packet(packet) {
  166. packet.nsp = this.nsp;
  167. this.io._packet(packet);
  168. }
  169. /**
  170. * Called upon engine `open`.
  171. *
  172. * @private
  173. */
  174. onopen() {
  175. if (typeof this.auth == "function") {
  176. this.auth((data) => {
  177. this.packet({ type: PacketType.CONNECT, data });
  178. });
  179. }
  180. else {
  181. this.packet({ type: PacketType.CONNECT, data: this.auth });
  182. }
  183. }
  184. /**
  185. * Called upon engine or manager `error`.
  186. *
  187. * @param err
  188. * @private
  189. */
  190. onerror(err) {
  191. if (!this.connected) {
  192. this.emitReserved("connect_error", err);
  193. }
  194. }
  195. /**
  196. * Called upon engine `close`.
  197. *
  198. * @param reason
  199. * @private
  200. */
  201. onclose(reason) {
  202. this.connected = false;
  203. this.disconnected = true;
  204. delete this.id;
  205. this.emitReserved("disconnect", reason);
  206. }
  207. /**
  208. * Called with socket packet.
  209. *
  210. * @param packet
  211. * @private
  212. */
  213. onpacket(packet) {
  214. const sameNamespace = packet.nsp === this.nsp;
  215. if (!sameNamespace)
  216. return;
  217. switch (packet.type) {
  218. case PacketType.CONNECT:
  219. if (packet.data && packet.data.sid) {
  220. const id = packet.data.sid;
  221. this.onconnect(id);
  222. }
  223. else {
  224. this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
  225. }
  226. break;
  227. case PacketType.EVENT:
  228. this.onevent(packet);
  229. break;
  230. case PacketType.BINARY_EVENT:
  231. this.onevent(packet);
  232. break;
  233. case PacketType.ACK:
  234. this.onack(packet);
  235. break;
  236. case PacketType.BINARY_ACK:
  237. this.onack(packet);
  238. break;
  239. case PacketType.DISCONNECT:
  240. this.ondisconnect();
  241. break;
  242. case PacketType.CONNECT_ERROR:
  243. this.destroy();
  244. const err = new Error(packet.data.message);
  245. // @ts-ignore
  246. err.data = packet.data.data;
  247. this.emitReserved("connect_error", err);
  248. break;
  249. }
  250. }
  251. /**
  252. * Called upon a server event.
  253. *
  254. * @param packet
  255. * @private
  256. */
  257. onevent(packet) {
  258. const args = packet.data || [];
  259. if (null != packet.id) {
  260. args.push(this.ack(packet.id));
  261. }
  262. if (this.connected) {
  263. this.emitEvent(args);
  264. }
  265. else {
  266. this.receiveBuffer.push(Object.freeze(args));
  267. }
  268. }
  269. emitEvent(args) {
  270. if (this._anyListeners && this._anyListeners.length) {
  271. const listeners = this._anyListeners.slice();
  272. for (const listener of listeners) {
  273. listener.apply(this, args);
  274. }
  275. }
  276. super.emit.apply(this, args);
  277. }
  278. /**
  279. * Produces an ack callback to emit with an event.
  280. *
  281. * @private
  282. */
  283. ack(id) {
  284. const self = this;
  285. let sent = false;
  286. return function (...args) {
  287. // prevent double callbacks
  288. if (sent)
  289. return;
  290. sent = true;
  291. self.packet({
  292. type: PacketType.ACK,
  293. id: id,
  294. data: args,
  295. });
  296. };
  297. }
  298. /**
  299. * Called upon a server acknowlegement.
  300. *
  301. * @param packet
  302. * @private
  303. */
  304. onack(packet) {
  305. const ack = this.acks[packet.id];
  306. if ("function" === typeof ack) {
  307. ack.apply(this, packet.data);
  308. delete this.acks[packet.id];
  309. }
  310. else {
  311. }
  312. }
  313. /**
  314. * Called upon server connect.
  315. *
  316. * @private
  317. */
  318. onconnect(id) {
  319. this.id = id;
  320. this.connected = true;
  321. this.disconnected = false;
  322. this.emitBuffered();
  323. this.emitReserved("connect");
  324. }
  325. /**
  326. * Emit buffered events (received and emitted).
  327. *
  328. * @private
  329. */
  330. emitBuffered() {
  331. this.receiveBuffer.forEach((args) => this.emitEvent(args));
  332. this.receiveBuffer = [];
  333. this.sendBuffer.forEach((packet) => this.packet(packet));
  334. this.sendBuffer = [];
  335. }
  336. /**
  337. * Called upon server disconnect.
  338. *
  339. * @private
  340. */
  341. ondisconnect() {
  342. this.destroy();
  343. this.onclose("io server disconnect");
  344. }
  345. /**
  346. * Called upon forced client/server side disconnections,
  347. * this method ensures the manager stops tracking us and
  348. * that reconnections don't get triggered for this.
  349. *
  350. * @private
  351. */
  352. destroy() {
  353. if (this.subs) {
  354. // clean subscriptions to avoid reconnections
  355. this.subs.forEach((subDestroy) => subDestroy());
  356. this.subs = undefined;
  357. }
  358. this.io["_destroy"](this);
  359. }
  360. /**
  361. * Disconnects the socket manually.
  362. *
  363. * @return self
  364. * @public
  365. */
  366. disconnect() {
  367. if (this.connected) {
  368. this.packet({ type: PacketType.DISCONNECT });
  369. }
  370. // remove socket from pool
  371. this.destroy();
  372. if (this.connected) {
  373. // fire events
  374. this.onclose("io client disconnect");
  375. }
  376. return this;
  377. }
  378. /**
  379. * Alias for disconnect()
  380. *
  381. * @return self
  382. * @public
  383. */
  384. close() {
  385. return this.disconnect();
  386. }
  387. /**
  388. * Sets the compress flag.
  389. *
  390. * @param compress - if `true`, compresses the sending data
  391. * @return self
  392. * @public
  393. */
  394. compress(compress) {
  395. this.flags.compress = compress;
  396. return this;
  397. }
  398. /**
  399. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  400. * ready to send messages.
  401. *
  402. * @returns self
  403. * @public
  404. */
  405. get volatile() {
  406. this.flags.volatile = true;
  407. return this;
  408. }
  409. /**
  410. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  411. * given number of milliseconds have elapsed without an acknowledgement from the server:
  412. *
  413. * ```
  414. * socket.timeout(5000).emit("my-event", (err) => {
  415. * if (err) {
  416. * // the server did not acknowledge the event in the given delay
  417. * }
  418. * });
  419. * ```
  420. *
  421. * @returns self
  422. * @public
  423. */
  424. timeout(timeout) {
  425. this.flags.timeout = timeout;
  426. return this;
  427. }
  428. /**
  429. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  430. * callback.
  431. *
  432. * @param listener
  433. * @public
  434. */
  435. onAny(listener) {
  436. this._anyListeners = this._anyListeners || [];
  437. this._anyListeners.push(listener);
  438. return this;
  439. }
  440. /**
  441. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  442. * callback. The listener is added to the beginning of the listeners array.
  443. *
  444. * @param listener
  445. * @public
  446. */
  447. prependAny(listener) {
  448. this._anyListeners = this._anyListeners || [];
  449. this._anyListeners.unshift(listener);
  450. return this;
  451. }
  452. /**
  453. * Removes the listener that will be fired when any event is emitted.
  454. *
  455. * @param listener
  456. * @public
  457. */
  458. offAny(listener) {
  459. if (!this._anyListeners) {
  460. return this;
  461. }
  462. if (listener) {
  463. const listeners = this._anyListeners;
  464. for (let i = 0; i < listeners.length; i++) {
  465. if (listener === listeners[i]) {
  466. listeners.splice(i, 1);
  467. return this;
  468. }
  469. }
  470. }
  471. else {
  472. this._anyListeners = [];
  473. }
  474. return this;
  475. }
  476. /**
  477. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  478. * e.g. to remove listeners.
  479. *
  480. * @public
  481. */
  482. listenersAny() {
  483. return this._anyListeners || [];
  484. }
  485. }