uniapp,h5

manager.js 11KB

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