You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.5 KiB

4 years ago
  1. 'use strict';
  2. /* global __webpack_dev_server_client__ */
  3. /* eslint-disable
  4. camelcase
  5. */
  6. // this SockJSClient is here as a default fallback, in case inline mode
  7. // is off or the client is not injected. This will be switched to
  8. // WebsocketClient when it becomes the default
  9. // important: the path to SockJSClient here is made to work in the 'client'
  10. // directory, but is updated via the webpack compilation when compiled from
  11. // the 'client-src' directory
  12. var Client = typeof __webpack_dev_server_client__ !== 'undefined' ? __webpack_dev_server_client__ : // eslint-disable-next-line import/no-unresolved
  13. require('./clients/SockJSClient');
  14. var retries = 0;
  15. var client = null;
  16. var socket = function initSocket(url, handlers) {
  17. client = new Client(url);
  18. client.onOpen(function () {
  19. retries = 0;
  20. });
  21. client.onClose(function () {
  22. if (retries === 0) {
  23. handlers.close();
  24. } // Try to reconnect.
  25. client = null; // After 10 retries stop trying, to prevent logspam.
  26. if (retries <= 10) {
  27. // Exponentially increase timeout to reconnect.
  28. // Respectfully copied from the package `got`.
  29. // eslint-disable-next-line no-mixed-operators, no-restricted-properties
  30. var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
  31. retries += 1;
  32. setTimeout(function () {
  33. socket(url, handlers);
  34. }, retryInMs);
  35. }
  36. });
  37. client.onMessage(function (data) {
  38. var msg = JSON.parse(data);
  39. if (handlers[msg.type]) {
  40. handlers[msg.type](msg.data);
  41. }
  42. });
  43. };
  44. module.exports = socket;