reconnecting-websocket.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import RNTimer from 'react-native-background-timer';
  2. class Event {
  3. constructor(type, target) {
  4. this.target = target;
  5. this.type = type;
  6. }
  7. }
  8. class ErrorEvent extends Event {
  9. constructor(error, target) {
  10. super('error', target);
  11. this.message = error.message;
  12. this.error = error;
  13. }
  14. }
  15. class CloseEvent extends Event {
  16. constructor(code = 1000, reason = '', target) {
  17. super('close', target);
  18. this.wasClean = true;
  19. this.code = code;
  20. this.reason = reason;
  21. }
  22. }
  23. /*!
  24. * Reconnecting WebSocket
  25. * by Pedro Ladaria <pedro.ladaria@gmail.com>
  26. * https://github.com/pladaria/reconnecting-websocket
  27. * License MIT
  28. */
  29. const _setTimeout = RNTimer ? (callback, time) => RNTimer.setTimeout(callback, time) : setTimeout;
  30. const _clearTimeout = RNTimer ? (time) => RNTimer.clearTimeout(time) : clearTimeout;
  31. const getGlobalWebSocket = () => {
  32. if (typeof WebSocket !== 'undefined') {
  33. // @ts-ignore
  34. return WebSocket;
  35. }
  36. };
  37. /**
  38. * Returns true if given argument looks like a WebSocket class
  39. */
  40. const isWebSocket = (w) => typeof w === 'function' && w.CLOSING === 2;
  41. const DEFAULT = {
  42. maxReconnectionDelay: 10000,
  43. minReconnectionDelay: 1000 + Math.random() * 4000,
  44. minUptime: 5000,
  45. reconnectionDelayGrowFactor: 1.3,
  46. connectionTimeout: 4000,
  47. maxRetries: Infinity,
  48. debug: false,
  49. };
  50. class ReconnectingWebSocket {
  51. constructor(url, protocols, options = {}) {
  52. this._listeners = {
  53. error: [],
  54. message: [],
  55. open: [],
  56. close: [],
  57. };
  58. this._retryCount = -1;
  59. this._shouldReconnect = true;
  60. this._connectLock = false;
  61. this._binaryType = 'blob';
  62. this.eventToHandler = new Map([
  63. ['open', this._handleOpen.bind(this)],
  64. ['close', this._handleClose.bind(this)],
  65. ['error', this._handleError.bind(this)],
  66. ['message', this._handleMessage.bind(this)],
  67. ]);
  68. /**
  69. * An event listener to be called when the WebSocket connection's readyState changes to CLOSED
  70. */
  71. this.onclose = undefined;
  72. /**
  73. * An event listener to be called when an error occurs
  74. */
  75. this.onerror = undefined;
  76. /**
  77. * An event listener to be called when a message is received from the server
  78. */
  79. this.onmessage = undefined;
  80. /**
  81. * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
  82. * this indicates that the connection is ready to send and receive data
  83. */
  84. this.onopen = undefined;
  85. this._url = url;
  86. this._protocols = protocols;
  87. this._options = options;
  88. this._connect();
  89. }
  90. static get CONNECTING() {
  91. return 0;
  92. }
  93. static get OPEN() {
  94. return 1;
  95. }
  96. static get CLOSING() {
  97. return 2;
  98. }
  99. static get CLOSED() {
  100. return 3;
  101. }
  102. get CONNECTING() {
  103. return ReconnectingWebSocket.CONNECTING;
  104. }
  105. get OPEN() {
  106. return ReconnectingWebSocket.OPEN;
  107. }
  108. get CLOSING() {
  109. return ReconnectingWebSocket.CLOSING;
  110. }
  111. get CLOSED() {
  112. return ReconnectingWebSocket.CLOSED;
  113. }
  114. get binaryType() {
  115. return this._ws ? this._ws.binaryType : this._binaryType;
  116. }
  117. set binaryType(value) {
  118. this._binaryType = value;
  119. if (this._ws) {
  120. // @ts-ignore
  121. this._ws.binaryType = value;
  122. }
  123. }
  124. /**
  125. * Returns the number or connection retries
  126. */
  127. get retryCount() {
  128. return Math.max(this._retryCount, 0);
  129. }
  130. /**
  131. * The number of bytes of data that have been queued using calls to send() but not yet
  132. * transmitted to the network. This value resets to zero once all queued data has been sent.
  133. * This value does not reset to zero when the connection is closed; if you keep calling send(),
  134. * this will continue to climb. Read only
  135. */
  136. get bufferedAmount() {
  137. return this._ws ? this._ws.bufferedAmount : 0;
  138. }
  139. /**
  140. * The extensions selected by the server. This is currently only the empty string or a list of
  141. * extensions as negotiated by the connection
  142. */
  143. get extensions() {
  144. return this._ws ? this._ws.extensions : '';
  145. }
  146. /**
  147. * A string indicating the name of the sub-protocol the server selected;
  148. * this will be one of the strings specified in the protocols parameter when creating the
  149. * WebSocket object
  150. */
  151. get protocol() {
  152. return this._ws ? this._ws.protocol : '';
  153. }
  154. /**
  155. * The current state of the connection; this is one of the Ready state constants
  156. */
  157. get readyState() {
  158. return this._ws ? this._ws.readyState : ReconnectingWebSocket.CONNECTING;
  159. }
  160. /**
  161. * The URL as resolved by the constructor
  162. */
  163. get url() {
  164. return this._ws ? this._ws.url : '';
  165. }
  166. /**
  167. * Closes the WebSocket connection or connection attempt, if any. If the connection is already
  168. * CLOSED, this method does nothing
  169. */
  170. close(code, reason) {
  171. this._shouldReconnect = false;
  172. if (!this._ws || this._ws.readyState === this.CLOSED) {
  173. return;
  174. }
  175. this._ws.close(code, reason);
  176. }
  177. /**
  178. * Closes the WebSocket connection or connection attempt and connects again.
  179. * Resets retry counter;
  180. */
  181. reconnect(code, reason) {
  182. this._shouldReconnect = true;
  183. this._retryCount = -1;
  184. if (!this._ws || this._ws.readyState === this.CLOSED) {
  185. this._connect();
  186. }
  187. this._disconnect(code, reason);
  188. this._connect();
  189. }
  190. /**
  191. * Enqueues the specified data to be transmitted to the server over the WebSocket connection
  192. */
  193. send(data) {
  194. if (this._ws) {
  195. this._ws.send(data);
  196. }
  197. }
  198. /**
  199. * Register an event handler of a specific event type
  200. */
  201. addEventListener(type, listener) {
  202. if (this._listeners[type]) {
  203. // @ts-ignore
  204. this._listeners[type].push(listener);
  205. }
  206. }
  207. /**
  208. * Removes an event listener
  209. */
  210. removeEventListener(type, listener) {
  211. if (this._listeners[type]) {
  212. // @ts-ignore
  213. this._listeners[type] = this._listeners[type].filter(l => l !== listener);
  214. }
  215. }
  216. _debug(...params) {
  217. if (this._options.debug) {
  218. // tslint:disable-next-line
  219. console.log('RWS>', ...params);
  220. }
  221. }
  222. _getNextDelay() {
  223. let delay = 0;
  224. if (this._retryCount > 0) {
  225. const { reconnectionDelayGrowFactor = DEFAULT.reconnectionDelayGrowFactor, minReconnectionDelay = DEFAULT.minReconnectionDelay, maxReconnectionDelay = DEFAULT.maxReconnectionDelay, } = this._options;
  226. delay =
  227. minReconnectionDelay + Math.pow(this._retryCount - 1, reconnectionDelayGrowFactor);
  228. if (delay > maxReconnectionDelay) {
  229. delay = maxReconnectionDelay;
  230. }
  231. }
  232. this._debug('next delay', delay);
  233. return delay;
  234. }
  235. _wait() {
  236. return new Promise(resolve => {
  237. _setTimeout(resolve, this._getNextDelay());
  238. });
  239. }
  240. /**
  241. * @return Promise<string>
  242. */
  243. _getNextUrl(urlProvider) {
  244. if (typeof urlProvider === 'string') {
  245. return Promise.resolve(urlProvider);
  246. }
  247. if (typeof urlProvider === 'function') {
  248. const url = urlProvider();
  249. if (typeof url === 'string') {
  250. return Promise.resolve(url);
  251. }
  252. if (url.then) {
  253. return url;
  254. }
  255. }
  256. throw Error('Invalid URL');
  257. }
  258. _connect() {
  259. if (this._connectLock) {
  260. return;
  261. }
  262. this._connectLock = true;
  263. const { maxRetries = DEFAULT.maxRetries, connectionTimeout = DEFAULT.connectionTimeout, WebSocket = getGlobalWebSocket(), } = this._options;
  264. if (this._retryCount >= maxRetries) {
  265. this._debug('max retries reached', this._retryCount, '>=', maxRetries);
  266. return;
  267. }
  268. this._retryCount++;
  269. this._debug('connect', this._retryCount);
  270. this._removeListeners();
  271. if (!isWebSocket(WebSocket)) {
  272. throw Error('No valid WebSocket class provided');
  273. }
  274. this._wait()
  275. .then(() => this._getNextUrl(this._url))
  276. .then(url => {
  277. this._debug('connect', { url, protocols: this._protocols });
  278. this._ws = new WebSocket(url, this._protocols);
  279. // @ts-ignore
  280. this._ws.binaryType = this._binaryType;
  281. this._connectLock = false;
  282. this._addListeners();
  283. this._connectTimeout = _setTimeout(() => this._handleTimeout(), connectionTimeout);
  284. });
  285. }
  286. _handleTimeout() {
  287. this._debug('timeout event');
  288. this._handleError(new ErrorEvent(Error('TIMEOUT'), this));
  289. }
  290. _disconnect(code, reason) {
  291. _clearTimeout(this._connectTimeout);
  292. if (!this._ws) {
  293. return;
  294. }
  295. this._removeListeners();
  296. try {
  297. this._ws.close(code, reason);
  298. this._handleClose(new CloseEvent(code, reason, this));
  299. }
  300. catch (error) {
  301. // ignore
  302. }
  303. }
  304. _acceptOpen() {
  305. this._retryCount = 0;
  306. }
  307. _handleOpen(event) {
  308. this._debug('open event');
  309. const { minUptime = DEFAULT.minUptime } = this._options;
  310. _clearTimeout(this._connectTimeout);
  311. this._uptimeTimeout = _setTimeout(() => this._acceptOpen(), minUptime);
  312. this._debug('assign binary type');
  313. // @ts-ignore
  314. this._ws.binaryType = this._binaryType;
  315. if (this.onopen) {
  316. this.onopen(event);
  317. }
  318. this._listeners.open.forEach(listener => listener(event));
  319. }
  320. _handleMessage(event) {
  321. this._debug('message event');
  322. if (this.onmessage) {
  323. this.onmessage(event);
  324. }
  325. this._listeners.message.forEach(listener => listener(event));
  326. }
  327. _handleError(event) {
  328. this._debug('error event', event.message);
  329. this._disconnect(undefined, event.message === 'TIMEOUT' ? 'timeout' : undefined);
  330. if (this.onerror) {
  331. this.onerror(event);
  332. }
  333. this._debug('exec error listeners');
  334. this._listeners.error.forEach(listener => listener(event));
  335. this._connect();
  336. }
  337. _handleClose(event) {
  338. this._debug('close event');
  339. if (this.onclose) {
  340. this.onclose(event);
  341. }
  342. this._listeners.close.forEach(listener => listener(event));
  343. }
  344. /**
  345. * Remove event listeners to WebSocket instance
  346. */
  347. _removeListeners() {
  348. if (!this._ws) {
  349. return;
  350. }
  351. this._debug('removeListeners');
  352. for (const [type, handler] of this.eventToHandler) {
  353. this._ws.removeEventListener(type, handler);
  354. }
  355. }
  356. /**
  357. * Assign event listeners to WebSocket instance
  358. */
  359. _addListeners() {
  360. this._debug('addListeners');
  361. for (const [type, handler] of this.eventToHandler) {
  362. this._ws.addEventListener(type, handler);
  363. }
  364. }
  365. }
  366. export default ReconnectingWebSocket;