uniapp,h5

socket.js 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. /**
  18. * A Socket is the fundamental class for interacting with the server.
  19. *
  20. * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
  21. *
  22. * @example
  23. * const socket = io();
  24. *
  25. * socket.on("connect", () => {
  26. * console.log("connected");
  27. * });
  28. *
  29. * // send an event to the server
  30. * socket.emit("foo", "bar");
  31. *
  32. * socket.on("foobar", () => {
  33. * // an event was received from the server
  34. * });
  35. *
  36. * // upon disconnection
  37. * socket.on("disconnect", (reason) => {
  38. * console.log(`disconnected due to ${reason}`);
  39. * });
  40. */
  41. export class Socket extends Emitter {
  42. /**
  43. * `Socket` constructor.
  44. */
  45. constructor(io, nsp, opts) {
  46. super();
  47. /**
  48. * Whether the socket is currently connected to the server.
  49. *
  50. * @example
  51. * const socket = io();
  52. *
  53. * socket.on("connect", () => {
  54. * console.log(socket.connected); // true
  55. * });
  56. *
  57. * socket.on("disconnect", () => {
  58. * console.log(socket.connected); // false
  59. * });
  60. */
  61. this.connected = false;
  62. /**
  63. * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
  64. * be transmitted by the server.
  65. */
  66. this.recovered = false;
  67. /**
  68. * Buffer for packets received before the CONNECT packet
  69. */
  70. this.receiveBuffer = [];
  71. /**
  72. * Buffer for packets that will be sent once the socket is connected
  73. */
  74. this.sendBuffer = [];
  75. /**
  76. * The queue of packets to be sent with retry in case of failure.
  77. *
  78. * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
  79. * @private
  80. */
  81. this._queue = [];
  82. /**
  83. * A sequence to generate the ID of the {@link QueuedPacket}.
  84. * @private
  85. */
  86. this._queueSeq = 0;
  87. this.ids = 0;
  88. /**
  89. * A map containing acknowledgement handlers.
  90. *
  91. * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
  92. *
  93. * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
  94. * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
  95. * - `const value = await socket.emitWithAck("test")`
  96. *
  97. * From those that don't:
  98. *
  99. * - `socket.emit("test", (value) => { ... });`
  100. *
  101. * In the first case, the handlers will be called with an error when:
  102. *
  103. * - the timeout is reached
  104. * - the socket gets disconnected
  105. *
  106. * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
  107. * an acknowledgement from the server.
  108. *
  109. * @private
  110. */
  111. this.acks = {};
  112. this.flags = {};
  113. this.io = io;
  114. this.nsp = nsp;
  115. if (opts && opts.auth) {
  116. this.auth = opts.auth;
  117. }
  118. this._opts = Object.assign({}, opts);
  119. if (this.io._autoConnect)
  120. this.open();
  121. }
  122. /**
  123. * Whether the socket is currently disconnected
  124. *
  125. * @example
  126. * const socket = io();
  127. *
  128. * socket.on("connect", () => {
  129. * console.log(socket.disconnected); // false
  130. * });
  131. *
  132. * socket.on("disconnect", () => {
  133. * console.log(socket.disconnected); // true
  134. * });
  135. */
  136. get disconnected() {
  137. return !this.connected;
  138. }
  139. /**
  140. * Subscribe to open, close and packet events
  141. *
  142. * @private
  143. */
  144. subEvents() {
  145. if (this.subs)
  146. return;
  147. const io = this.io;
  148. this.subs = [
  149. on(io, "open", this.onopen.bind(this)),
  150. on(io, "packet", this.onpacket.bind(this)),
  151. on(io, "error", this.onerror.bind(this)),
  152. on(io, "close", this.onclose.bind(this)),
  153. ];
  154. }
  155. /**
  156. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  157. *
  158. * @example
  159. * const socket = io();
  160. *
  161. * console.log(socket.active); // true
  162. *
  163. * socket.on("disconnect", (reason) => {
  164. * if (reason === "io server disconnect") {
  165. * // the disconnection was initiated by the server, you need to manually reconnect
  166. * console.log(socket.active); // false
  167. * }
  168. * // else the socket will automatically try to reconnect
  169. * console.log(socket.active); // true
  170. * });
  171. */
  172. get active() {
  173. return !!this.subs;
  174. }
  175. /**
  176. * "Opens" the socket.
  177. *
  178. * @example
  179. * const socket = io({
  180. * autoConnect: false
  181. * });
  182. *
  183. * socket.connect();
  184. */
  185. connect() {
  186. if (this.connected)
  187. return this;
  188. this.subEvents();
  189. if (!this.io["_reconnecting"])
  190. this.io.open(); // ensure open
  191. if ("open" === this.io._readyState)
  192. this.onopen();
  193. return this;
  194. }
  195. /**
  196. * Alias for {@link connect()}.
  197. */
  198. open() {
  199. return this.connect();
  200. }
  201. /**
  202. * Sends a `message` event.
  203. *
  204. * This method mimics the WebSocket.send() method.
  205. *
  206. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  207. *
  208. * @example
  209. * socket.send("hello");
  210. *
  211. * // this is equivalent to
  212. * socket.emit("message", "hello");
  213. *
  214. * @return self
  215. */
  216. send(...args) {
  217. args.unshift("message");
  218. this.emit.apply(this, args);
  219. return this;
  220. }
  221. /**
  222. * Override `emit`.
  223. * If the event is in `events`, it's emitted normally.
  224. *
  225. * @example
  226. * socket.emit("hello", "world");
  227. *
  228. * // all serializable datastructures are supported (no need to call JSON.stringify)
  229. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  230. *
  231. * // with an acknowledgement from the server
  232. * socket.emit("hello", "world", (val) => {
  233. * // ...
  234. * });
  235. *
  236. * @return self
  237. */
  238. emit(ev, ...args) {
  239. var _a, _b, _c;
  240. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  241. throw new Error('"' + ev.toString() + '" is a reserved event name');
  242. }
  243. args.unshift(ev);
  244. if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
  245. this._addToQueue(args);
  246. return this;
  247. }
  248. const packet = {
  249. type: PacketType.EVENT,
  250. data: args,
  251. };
  252. packet.options = {};
  253. packet.options.compress = this.flags.compress !== false;
  254. // event ack callback
  255. if ("function" === typeof args[args.length - 1]) {
  256. const id = this.ids++;
  257. const ack = args.pop();
  258. this._registerAckCallback(id, ack);
  259. packet.id = id;
  260. }
  261. const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
  262. const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
  263. const discardPacket = this.flags.volatile && !isTransportWritable;
  264. if (discardPacket) {
  265. }
  266. else if (isConnected) {
  267. this.notifyOutgoingListeners(packet);
  268. this.packet(packet);
  269. }
  270. else {
  271. this.sendBuffer.push(packet);
  272. }
  273. this.flags = {};
  274. return this;
  275. }
  276. /**
  277. * @private
  278. */
  279. _registerAckCallback(id, ack) {
  280. var _a;
  281. const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
  282. if (timeout === undefined) {
  283. this.acks[id] = ack;
  284. return;
  285. }
  286. // @ts-ignore
  287. const timer = this.io.setTimeoutFn(() => {
  288. delete this.acks[id];
  289. for (let i = 0; i < this.sendBuffer.length; i++) {
  290. if (this.sendBuffer[i].id === id) {
  291. this.sendBuffer.splice(i, 1);
  292. }
  293. }
  294. ack.call(this, new Error("operation has timed out"));
  295. }, timeout);
  296. const fn = (...args) => {
  297. // @ts-ignore
  298. this.io.clearTimeoutFn(timer);
  299. ack.apply(this, args);
  300. };
  301. fn.withError = true;
  302. this.acks[id] = fn;
  303. }
  304. /**
  305. * Emits an event and waits for an acknowledgement
  306. *
  307. * @example
  308. * // without timeout
  309. * const response = await socket.emitWithAck("hello", "world");
  310. *
  311. * // with a specific timeout
  312. * try {
  313. * const response = await socket.timeout(1000).emitWithAck("hello", "world");
  314. * } catch (err) {
  315. * // the server did not acknowledge the event in the given delay
  316. * }
  317. *
  318. * @return a Promise that will be fulfilled when the server acknowledges the event
  319. */
  320. emitWithAck(ev, ...args) {
  321. return new Promise((resolve, reject) => {
  322. const fn = (arg1, arg2) => {
  323. return arg1 ? reject(arg1) : resolve(arg2);
  324. };
  325. fn.withError = true;
  326. args.push(fn);
  327. this.emit(ev, ...args);
  328. });
  329. }
  330. /**
  331. * Add the packet to the queue.
  332. * @param args
  333. * @private
  334. */
  335. _addToQueue(args) {
  336. let ack;
  337. if (typeof args[args.length - 1] === "function") {
  338. ack = args.pop();
  339. }
  340. const packet = {
  341. id: this._queueSeq++,
  342. tryCount: 0,
  343. pending: false,
  344. args,
  345. flags: Object.assign({ fromQueue: true }, this.flags),
  346. };
  347. args.push((err, ...responseArgs) => {
  348. if (packet !== this._queue[0]) {
  349. // the packet has already been acknowledged
  350. return;
  351. }
  352. const hasError = err !== null;
  353. if (hasError) {
  354. if (packet.tryCount > this._opts.retries) {
  355. this._queue.shift();
  356. if (ack) {
  357. ack(err);
  358. }
  359. }
  360. }
  361. else {
  362. this._queue.shift();
  363. if (ack) {
  364. ack(null, ...responseArgs);
  365. }
  366. }
  367. packet.pending = false;
  368. return this._drainQueue();
  369. });
  370. this._queue.push(packet);
  371. this._drainQueue();
  372. }
  373. /**
  374. * Send the first packet of the queue, and wait for an acknowledgement from the server.
  375. * @param force - whether to resend a packet that has not been acknowledged yet
  376. *
  377. * @private
  378. */
  379. _drainQueue(force = false) {
  380. if (!this.connected || this._queue.length === 0) {
  381. return;
  382. }
  383. const packet = this._queue[0];
  384. if (packet.pending && !force) {
  385. return;
  386. }
  387. packet.pending = true;
  388. packet.tryCount++;
  389. this.flags = packet.flags;
  390. this.emit.apply(this, packet.args);
  391. }
  392. /**
  393. * Sends a packet.
  394. *
  395. * @param packet
  396. * @private
  397. */
  398. packet(packet) {
  399. packet.nsp = this.nsp;
  400. this.io._packet(packet);
  401. }
  402. /**
  403. * Called upon engine `open`.
  404. *
  405. * @private
  406. */
  407. onopen() {
  408. if (typeof this.auth == "function") {
  409. this.auth((data) => {
  410. this._sendConnectPacket(data);
  411. });
  412. }
  413. else {
  414. this._sendConnectPacket(this.auth);
  415. }
  416. }
  417. /**
  418. * Sends a CONNECT packet to initiate the Socket.IO session.
  419. *
  420. * @param data
  421. * @private
  422. */
  423. _sendConnectPacket(data) {
  424. this.packet({
  425. type: PacketType.CONNECT,
  426. data: this._pid
  427. ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
  428. : data,
  429. });
  430. }
  431. /**
  432. * Called upon engine or manager `error`.
  433. *
  434. * @param err
  435. * @private
  436. */
  437. onerror(err) {
  438. if (!this.connected) {
  439. this.emitReserved("connect_error", err);
  440. }
  441. }
  442. /**
  443. * Called upon engine `close`.
  444. *
  445. * @param reason
  446. * @param description
  447. * @private
  448. */
  449. onclose(reason, description) {
  450. this.connected = false;
  451. delete this.id;
  452. this.emitReserved("disconnect", reason, description);
  453. this._clearAcks();
  454. }
  455. /**
  456. * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
  457. * the server.
  458. *
  459. * @private
  460. */
  461. _clearAcks() {
  462. Object.keys(this.acks).forEach((id) => {
  463. const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
  464. if (!isBuffered) {
  465. // note: handlers that do not accept an error as first argument are ignored here
  466. const ack = this.acks[id];
  467. delete this.acks[id];
  468. if (ack.withError) {
  469. ack.call(this, new Error("socket has been disconnected"));
  470. }
  471. }
  472. });
  473. }
  474. /**
  475. * Called with socket packet.
  476. *
  477. * @param packet
  478. * @private
  479. */
  480. onpacket(packet) {
  481. const sameNamespace = packet.nsp === this.nsp;
  482. if (!sameNamespace)
  483. return;
  484. switch (packet.type) {
  485. case PacketType.CONNECT:
  486. if (packet.data && packet.data.sid) {
  487. this.onconnect(packet.data.sid, packet.data.pid);
  488. }
  489. else {
  490. 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/)"));
  491. }
  492. break;
  493. case PacketType.EVENT:
  494. case PacketType.BINARY_EVENT:
  495. this.onevent(packet);
  496. break;
  497. case PacketType.ACK:
  498. case PacketType.BINARY_ACK:
  499. this.onack(packet);
  500. break;
  501. case PacketType.DISCONNECT:
  502. this.ondisconnect();
  503. break;
  504. case PacketType.CONNECT_ERROR:
  505. this.destroy();
  506. const err = new Error(packet.data.message);
  507. // @ts-ignore
  508. err.data = packet.data.data;
  509. this.emitReserved("connect_error", err);
  510. break;
  511. }
  512. }
  513. /**
  514. * Called upon a server event.
  515. *
  516. * @param packet
  517. * @private
  518. */
  519. onevent(packet) {
  520. const args = packet.data || [];
  521. if (null != packet.id) {
  522. args.push(this.ack(packet.id));
  523. }
  524. if (this.connected) {
  525. this.emitEvent(args);
  526. }
  527. else {
  528. this.receiveBuffer.push(Object.freeze(args));
  529. }
  530. }
  531. emitEvent(args) {
  532. if (this._anyListeners && this._anyListeners.length) {
  533. const listeners = this._anyListeners.slice();
  534. for (const listener of listeners) {
  535. listener.apply(this, args);
  536. }
  537. }
  538. super.emit.apply(this, args);
  539. if (this._pid && args.length && typeof args[args.length - 1] === "string") {
  540. this._lastOffset = args[args.length - 1];
  541. }
  542. }
  543. /**
  544. * Produces an ack callback to emit with an event.
  545. *
  546. * @private
  547. */
  548. ack(id) {
  549. const self = this;
  550. let sent = false;
  551. return function (...args) {
  552. // prevent double callbacks
  553. if (sent)
  554. return;
  555. sent = true;
  556. self.packet({
  557. type: PacketType.ACK,
  558. id: id,
  559. data: args,
  560. });
  561. };
  562. }
  563. /**
  564. * Called upon a server acknowledgement.
  565. *
  566. * @param packet
  567. * @private
  568. */
  569. onack(packet) {
  570. const ack = this.acks[packet.id];
  571. if (typeof ack !== "function") {
  572. return;
  573. }
  574. delete this.acks[packet.id];
  575. // @ts-ignore FIXME ack is incorrectly inferred as 'never'
  576. if (ack.withError) {
  577. packet.data.unshift(null);
  578. }
  579. // @ts-ignore
  580. ack.apply(this, packet.data);
  581. }
  582. /**
  583. * Called upon server connect.
  584. *
  585. * @private
  586. */
  587. onconnect(id, pid) {
  588. this.id = id;
  589. this.recovered = pid && this._pid === pid;
  590. this._pid = pid; // defined only if connection state recovery is enabled
  591. this.connected = true;
  592. this.emitBuffered();
  593. this.emitReserved("connect");
  594. this._drainQueue(true);
  595. }
  596. /**
  597. * Emit buffered events (received and emitted).
  598. *
  599. * @private
  600. */
  601. emitBuffered() {
  602. this.receiveBuffer.forEach((args) => this.emitEvent(args));
  603. this.receiveBuffer = [];
  604. this.sendBuffer.forEach((packet) => {
  605. this.notifyOutgoingListeners(packet);
  606. this.packet(packet);
  607. });
  608. this.sendBuffer = [];
  609. }
  610. /**
  611. * Called upon server disconnect.
  612. *
  613. * @private
  614. */
  615. ondisconnect() {
  616. this.destroy();
  617. this.onclose("io server disconnect");
  618. }
  619. /**
  620. * Called upon forced client/server side disconnections,
  621. * this method ensures the manager stops tracking us and
  622. * that reconnections don't get triggered for this.
  623. *
  624. * @private
  625. */
  626. destroy() {
  627. if (this.subs) {
  628. // clean subscriptions to avoid reconnections
  629. this.subs.forEach((subDestroy) => subDestroy());
  630. this.subs = undefined;
  631. }
  632. this.io["_destroy"](this);
  633. }
  634. /**
  635. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  636. *
  637. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  638. *
  639. * @example
  640. * const socket = io();
  641. *
  642. * socket.on("disconnect", (reason) => {
  643. * // console.log(reason); prints "io client disconnect"
  644. * });
  645. *
  646. * socket.disconnect();
  647. *
  648. * @return self
  649. */
  650. disconnect() {
  651. if (this.connected) {
  652. this.packet({ type: PacketType.DISCONNECT });
  653. }
  654. // remove socket from pool
  655. this.destroy();
  656. if (this.connected) {
  657. // fire events
  658. this.onclose("io client disconnect");
  659. }
  660. return this;
  661. }
  662. /**
  663. * Alias for {@link disconnect()}.
  664. *
  665. * @return self
  666. */
  667. close() {
  668. return this.disconnect();
  669. }
  670. /**
  671. * Sets the compress flag.
  672. *
  673. * @example
  674. * socket.compress(false).emit("hello");
  675. *
  676. * @param compress - if `true`, compresses the sending data
  677. * @return self
  678. */
  679. compress(compress) {
  680. this.flags.compress = compress;
  681. return this;
  682. }
  683. /**
  684. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  685. * ready to send messages.
  686. *
  687. * @example
  688. * socket.volatile.emit("hello"); // the server may or may not receive it
  689. *
  690. * @returns self
  691. */
  692. get volatile() {
  693. this.flags.volatile = true;
  694. return this;
  695. }
  696. /**
  697. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  698. * given number of milliseconds have elapsed without an acknowledgement from the server:
  699. *
  700. * @example
  701. * socket.timeout(5000).emit("my-event", (err) => {
  702. * if (err) {
  703. * // the server did not acknowledge the event in the given delay
  704. * }
  705. * });
  706. *
  707. * @returns self
  708. */
  709. timeout(timeout) {
  710. this.flags.timeout = timeout;
  711. return this;
  712. }
  713. /**
  714. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  715. * callback.
  716. *
  717. * @example
  718. * socket.onAny((event, ...args) => {
  719. * console.log(`got ${event}`);
  720. * });
  721. *
  722. * @param listener
  723. */
  724. onAny(listener) {
  725. this._anyListeners = this._anyListeners || [];
  726. this._anyListeners.push(listener);
  727. return this;
  728. }
  729. /**
  730. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  731. * callback. The listener is added to the beginning of the listeners array.
  732. *
  733. * @example
  734. * socket.prependAny((event, ...args) => {
  735. * console.log(`got event ${event}`);
  736. * });
  737. *
  738. * @param listener
  739. */
  740. prependAny(listener) {
  741. this._anyListeners = this._anyListeners || [];
  742. this._anyListeners.unshift(listener);
  743. return this;
  744. }
  745. /**
  746. * Removes the listener that will be fired when any event is emitted.
  747. *
  748. * @example
  749. * const catchAllListener = (event, ...args) => {
  750. * console.log(`got event ${event}`);
  751. * }
  752. *
  753. * socket.onAny(catchAllListener);
  754. *
  755. * // remove a specific listener
  756. * socket.offAny(catchAllListener);
  757. *
  758. * // or remove all listeners
  759. * socket.offAny();
  760. *
  761. * @param listener
  762. */
  763. offAny(listener) {
  764. if (!this._anyListeners) {
  765. return this;
  766. }
  767. if (listener) {
  768. const listeners = this._anyListeners;
  769. for (let i = 0; i < listeners.length; i++) {
  770. if (listener === listeners[i]) {
  771. listeners.splice(i, 1);
  772. return this;
  773. }
  774. }
  775. }
  776. else {
  777. this._anyListeners = [];
  778. }
  779. return this;
  780. }
  781. /**
  782. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  783. * e.g. to remove listeners.
  784. */
  785. listenersAny() {
  786. return this._anyListeners || [];
  787. }
  788. /**
  789. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  790. * callback.
  791. *
  792. * Note: acknowledgements sent to the server are not included.
  793. *
  794. * @example
  795. * socket.onAnyOutgoing((event, ...args) => {
  796. * console.log(`sent event ${event}`);
  797. * });
  798. *
  799. * @param listener
  800. */
  801. onAnyOutgoing(listener) {
  802. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  803. this._anyOutgoingListeners.push(listener);
  804. return this;
  805. }
  806. /**
  807. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  808. * callback. The listener is added to the beginning of the listeners array.
  809. *
  810. * Note: acknowledgements sent to the server are not included.
  811. *
  812. * @example
  813. * socket.prependAnyOutgoing((event, ...args) => {
  814. * console.log(`sent event ${event}`);
  815. * });
  816. *
  817. * @param listener
  818. */
  819. prependAnyOutgoing(listener) {
  820. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  821. this._anyOutgoingListeners.unshift(listener);
  822. return this;
  823. }
  824. /**
  825. * Removes the listener that will be fired when any event is emitted.
  826. *
  827. * @example
  828. * const catchAllListener = (event, ...args) => {
  829. * console.log(`sent event ${event}`);
  830. * }
  831. *
  832. * socket.onAnyOutgoing(catchAllListener);
  833. *
  834. * // remove a specific listener
  835. * socket.offAnyOutgoing(catchAllListener);
  836. *
  837. * // or remove all listeners
  838. * socket.offAnyOutgoing();
  839. *
  840. * @param [listener] - the catch-all listener (optional)
  841. */
  842. offAnyOutgoing(listener) {
  843. if (!this._anyOutgoingListeners) {
  844. return this;
  845. }
  846. if (listener) {
  847. const listeners = this._anyOutgoingListeners;
  848. for (let i = 0; i < listeners.length; i++) {
  849. if (listener === listeners[i]) {
  850. listeners.splice(i, 1);
  851. return this;
  852. }
  853. }
  854. }
  855. else {
  856. this._anyOutgoingListeners = [];
  857. }
  858. return this;
  859. }
  860. /**
  861. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  862. * e.g. to remove listeners.
  863. */
  864. listenersAnyOutgoing() {
  865. return this._anyOutgoingListeners || [];
  866. }
  867. /**
  868. * Notify the listeners for each packet sent
  869. *
  870. * @param packet
  871. *
  872. * @private
  873. */
  874. notifyOutgoingListeners(packet) {
  875. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  876. const listeners = this._anyOutgoingListeners.slice();
  877. for (const listener of listeners) {
  878. listener.apply(this, packet.data);
  879. }
  880. }
  881. }
  882. }