socket.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var SockJS = require('sockjs-client/dist/sockjs');
  3. var retries = 0;
  4. var sock = null;
  5. var socket = function initSocket(url, handlers) {
  6. sock = new SockJS(url);
  7. sock.onopen = function onopen() {
  8. retries = 0;
  9. };
  10. sock.onclose = function onclose() {
  11. if (retries === 0) {
  12. handlers.close();
  13. } // Try to reconnect.
  14. sock = null; // After 10 retries stop trying, to prevent logspam.
  15. if (retries <= 10) {
  16. // Exponentially increase timeout to reconnect.
  17. // Respectfully copied from the package `got`.
  18. // eslint-disable-next-line no-mixed-operators, no-restricted-properties
  19. var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
  20. retries += 1;
  21. setTimeout(function () {
  22. socket(url, handlers);
  23. }, retryInMs);
  24. }
  25. };
  26. sock.onmessage = function onmessage(e) {
  27. // This assumes that all data sent via the websocket is JSON.
  28. var msg = JSON.parse(e.data);
  29. if (handlers[msg.type]) {
  30. handlers[msg.type](msg.data);
  31. }
  32. };
  33. };
  34. module.exports = socket;