uniapp,h5

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import { Socket as Engine, installTimerFunctions, nextTick, } from "engine.io-client";
  2. import { Socket } from "./socket.js";
  3. import * as parser from "socket.io-parser";
  4. import { on } from "./on.js";
  5. import { Backoff } from "./contrib/backo2.js";
  6. import { Emitter, } from "@socket.io/component-emitter";
  7. export class Manager extends Emitter {
  8. constructor(uri, opts) {
  9. var _a;
  10. super();
  11. this.nsps = {};
  12. this.subs = [];
  13. if (uri && "object" === typeof uri) {
  14. opts = uri;
  15. uri = undefined;
  16. }
  17. opts = opts || {};
  18. opts.path = opts.path || "/socket.io";
  19. this.opts = opts;
  20. installTimerFunctions(this, opts);
  21. this.reconnection(opts.reconnection !== false);
  22. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  23. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  24. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  25. this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  26. this.backoff = new Backoff({
  27. min: this.reconnectionDelay(),
  28. max: this.reconnectionDelayMax(),
  29. jitter: this.randomizationFactor(),
  30. });
  31. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  32. this._readyState = "closed";
  33. this.uri = uri;
  34. const _parser = opts.parser || parser;
  35. this.encoder = new _parser.Encoder();
  36. this.decoder = new _parser.Decoder();
  37. this._autoConnect = opts.autoConnect !== false;
  38. if (this._autoConnect)
  39. this.open();
  40. }
  41. reconnection(v) {
  42. if (!arguments.length)
  43. return this._reconnection;
  44. this._reconnection = !!v;
  45. if (!v) {
  46. this.skipReconnect = true;
  47. }
  48. return this;
  49. }
  50. reconnectionAttempts(v) {
  51. if (v === undefined)
  52. return this._reconnectionAttempts;
  53. this._reconnectionAttempts = v;
  54. return this;
  55. }
  56. reconnectionDelay(v) {
  57. var _a;
  58. if (v === undefined)
  59. return this._reconnectionDelay;
  60. this._reconnectionDelay = v;
  61. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  62. return this;
  63. }
  64. randomizationFactor(v) {
  65. var _a;
  66. if (v === undefined)
  67. return this._randomizationFactor;
  68. this._randomizationFactor = v;
  69. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  70. return this;
  71. }
  72. reconnectionDelayMax(v) {
  73. var _a;
  74. if (v === undefined)
  75. return this._reconnectionDelayMax;
  76. this._reconnectionDelayMax = v;
  77. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  78. return this;
  79. }
  80. timeout(v) {
  81. if (!arguments.length)
  82. return this._timeout;
  83. this._timeout = v;
  84. return this;
  85. }
  86. /**
  87. * Starts trying to reconnect if reconnection is enabled and we have not
  88. * started reconnecting yet
  89. *
  90. * @private
  91. */
  92. maybeReconnectOnOpen() {
  93. // Only try to reconnect if it's the first time we're connecting
  94. if (!this._reconnecting &&
  95. this._reconnection &&
  96. this.backoff.attempts === 0) {
  97. // keeps reconnection from firing twice for the same reconnection loop
  98. this.reconnect();
  99. }
  100. }
  101. /**
  102. * Sets the current transport `socket`.
  103. *
  104. * @param {Function} fn - optional, callback
  105. * @return self
  106. * @public
  107. */
  108. open(fn) {
  109. if (~this._readyState.indexOf("open"))
  110. return this;
  111. this.engine = new Engine(this.uri, this.opts);
  112. const socket = this.engine;
  113. const self = this;
  114. this._readyState = "opening";
  115. this.skipReconnect = false;
  116. // emit `open`
  117. const openSubDestroy = on(socket, "open", function () {
  118. self.onopen();
  119. fn && fn();
  120. });
  121. const onError = (err) => {
  122. this.cleanup();
  123. this._readyState = "closed";
  124. this.emitReserved("error", err);
  125. if (fn) {
  126. fn(err);
  127. }
  128. else {
  129. // Only do this if there is no fn to handle the error
  130. this.maybeReconnectOnOpen();
  131. }
  132. };
  133. // emit `error`
  134. const errorSub = on(socket, "error", onError);
  135. if (false !== this._timeout) {
  136. const timeout = this._timeout;
  137. // set timer
  138. const timer = this.setTimeoutFn(() => {
  139. openSubDestroy();
  140. onError(new Error("timeout"));
  141. socket.close();
  142. }, timeout);
  143. if (this.opts.autoUnref) {
  144. timer.unref();
  145. }
  146. this.subs.push(() => {
  147. this.clearTimeoutFn(timer);
  148. });
  149. }
  150. this.subs.push(openSubDestroy);
  151. this.subs.push(errorSub);
  152. return this;
  153. }
  154. /**
  155. * Alias for open()
  156. *
  157. * @return self
  158. * @public
  159. */
  160. connect(fn) {
  161. return this.open(fn);
  162. }
  163. /**
  164. * Called upon transport open.
  165. *
  166. * @private
  167. */
  168. onopen() {
  169. // clear old subs
  170. this.cleanup();
  171. // mark as open
  172. this._readyState = "open";
  173. this.emitReserved("open");
  174. // add new subs
  175. const socket = this.engine;
  176. this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)),
  177. // @ts-ignore
  178. on(this.decoder, "decoded", this.ondecoded.bind(this)));
  179. }
  180. /**
  181. * Called upon a ping.
  182. *
  183. * @private
  184. */
  185. onping() {
  186. this.emitReserved("ping");
  187. }
  188. /**
  189. * Called with data.
  190. *
  191. * @private
  192. */
  193. ondata(data) {
  194. try {
  195. this.decoder.add(data);
  196. }
  197. catch (e) {
  198. this.onclose("parse error", e);
  199. }
  200. }
  201. /**
  202. * Called when parser fully decodes a packet.
  203. *
  204. * @private
  205. */
  206. ondecoded(packet) {
  207. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  208. nextTick(() => {
  209. this.emitReserved("packet", packet);
  210. }, this.setTimeoutFn);
  211. }
  212. /**
  213. * Called upon socket error.
  214. *
  215. * @private
  216. */
  217. onerror(err) {
  218. this.emitReserved("error", err);
  219. }
  220. /**
  221. * Creates a new socket for the given `nsp`.
  222. *
  223. * @return {Socket}
  224. * @public
  225. */
  226. socket(nsp, opts) {
  227. let socket = this.nsps[nsp];
  228. if (!socket) {
  229. socket = new Socket(this, nsp, opts);
  230. this.nsps[nsp] = socket;
  231. }
  232. else if (this._autoConnect && !socket.active) {
  233. socket.connect();
  234. }
  235. return socket;
  236. }
  237. /**
  238. * Called upon a socket close.
  239. *
  240. * @param socket
  241. * @private
  242. */
  243. _destroy(socket) {
  244. const nsps = Object.keys(this.nsps);
  245. for (const nsp of nsps) {
  246. const socket = this.nsps[nsp];
  247. if (socket.active) {
  248. return;
  249. }
  250. }
  251. this._close();
  252. }
  253. /**
  254. * Writes a packet.
  255. *
  256. * @param packet
  257. * @private
  258. */
  259. _packet(packet) {
  260. const encodedPackets = this.encoder.encode(packet);
  261. for (let i = 0; i < encodedPackets.length; i++) {
  262. this.engine.write(encodedPackets[i], packet.options);
  263. }
  264. }
  265. /**
  266. * Clean up transport subscriptions and packet buffer.
  267. *
  268. * @private
  269. */
  270. cleanup() {
  271. this.subs.forEach((subDestroy) => subDestroy());
  272. this.subs.length = 0;
  273. this.decoder.destroy();
  274. }
  275. /**
  276. * Close the current socket.
  277. *
  278. * @private
  279. */
  280. _close() {
  281. this.skipReconnect = true;
  282. this._reconnecting = false;
  283. this.onclose("forced close");
  284. }
  285. /**
  286. * Alias for close()
  287. *
  288. * @private
  289. */
  290. disconnect() {
  291. return this._close();
  292. }
  293. /**
  294. * Called when:
  295. *
  296. * - the low-level engine is closed
  297. * - the parser encountered a badly formatted packet
  298. * - all sockets are disconnected
  299. *
  300. * @private
  301. */
  302. onclose(reason, description) {
  303. var _a;
  304. this.cleanup();
  305. (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
  306. this.backoff.reset();
  307. this._readyState = "closed";
  308. this.emitReserved("close", reason, description);
  309. if (this._reconnection && !this.skipReconnect) {
  310. this.reconnect();
  311. }
  312. }
  313. /**
  314. * Attempt a reconnection.
  315. *
  316. * @private
  317. */
  318. reconnect() {
  319. if (this._reconnecting || this.skipReconnect)
  320. return this;
  321. const self = this;
  322. if (this.backoff.attempts >= this._reconnectionAttempts) {
  323. this.backoff.reset();
  324. this.emitReserved("reconnect_failed");
  325. this._reconnecting = false;
  326. }
  327. else {
  328. const delay = this.backoff.duration();
  329. this._reconnecting = true;
  330. const timer = this.setTimeoutFn(() => {
  331. if (self.skipReconnect)
  332. return;
  333. this.emitReserved("reconnect_attempt", self.backoff.attempts);
  334. // check again for the case socket closed in above events
  335. if (self.skipReconnect)
  336. return;
  337. self.open((err) => {
  338. if (err) {
  339. self._reconnecting = false;
  340. self.reconnect();
  341. this.emitReserved("reconnect_error", err);
  342. }
  343. else {
  344. self.onreconnect();
  345. }
  346. });
  347. }, delay);
  348. if (this.opts.autoUnref) {
  349. timer.unref();
  350. }
  351. this.subs.push(() => {
  352. this.clearTimeoutFn(timer);
  353. });
  354. }
  355. }
  356. /**
  357. * Called upon successful reconnect.
  358. *
  359. * @private
  360. */
  361. onreconnect() {
  362. const attempt = this.backoff.attempts;
  363. this._reconnecting = false;
  364. this.backoff.reset();
  365. this.emitReserved("reconnect", attempt);
  366. }
  367. }