1 | var HuntingWebsocket, ReconnectingWebSocket;
|
2 |
|
3 | ReconnectingWebSocket = require('./reconnecting-websocket');
|
4 |
|
5 | HuntingWebsocket = (function() {
|
6 | function HuntingWebsocket(urls) {
|
7 | var openAtAll, socket, url, _i, _len, _ref;
|
8 | this.urls = urls;
|
9 | openAtAll = false;
|
10 | this.lastSocket = void 0;
|
11 | this.sockets = [];
|
12 | _ref = this.urls;
|
13 | for (_i = 0, _len = _ref.length; _i < _len; _i++) {
|
14 | url = _ref[_i];
|
15 | socket = new ReconnectingWebSocket(url);
|
16 | this.sockets.push(socket);
|
17 | socket.onmessage = (function(_this) {
|
18 | return function(evt) {
|
19 | return _this.onmessage(evt);
|
20 | };
|
21 | })(this);
|
22 | socket.onerror = (function(_this) {
|
23 | return function(err) {
|
24 | return _this.onerror(err);
|
25 | };
|
26 | })(this);
|
27 | socket.onopen = (function(_this) {
|
28 | return function(evt) {
|
29 | if (!openAtAll) {
|
30 | openAtAll = true;
|
31 | return _this.onopen(evt);
|
32 | }
|
33 | };
|
34 | })(this);
|
35 | socket.onreconnect = (function(_this) {
|
36 | return function(evt) {
|
37 | return _this.onreconnect(evt);
|
38 | };
|
39 | })(this);
|
40 | }
|
41 | this.forceclose = false;
|
42 | }
|
43 |
|
44 | HuntingWebsocket.prototype.send = function(data) {
|
45 | var err, socket, trySockets, _i, _len, _ref;
|
46 | trySockets = this.sockets.slice(0);
|
47 | if (this.lastSocket) {
|
48 | trySockets.unshift(this.lastSocket);
|
49 | }
|
50 | for (_i = 0, _len = trySockets.length; _i < _len; _i++) {
|
51 | socket = trySockets[_i];
|
52 | try {
|
53 | if (socket.readyState === WebSocket.OPEN) {
|
54 | console.log('Sending message to ', socket.url);
|
55 | socket.send(data);
|
56 | if (socket.url !== ((_ref = this.lastSocket) != null ? _ref.url : void 0)) {
|
57 | this.lastSocket = socket;
|
58 | this.onserver({
|
59 | server: socket.url
|
60 | });
|
61 | }
|
62 | return;
|
63 | } else {
|
64 | socket.connect();
|
65 | }
|
66 | } catch (_error) {
|
67 | err = _error;
|
68 | this.onerror(err);
|
69 | }
|
70 | }
|
71 | };
|
72 |
|
73 | HuntingWebsocket.prototype.close = function() {
|
74 | var socket, _i, _len, _ref;
|
75 | _ref = this.sockets;
|
76 | for (_i = 0, _len = _ref.length; _i < _len; _i++) {
|
77 | socket = _ref[_i];
|
78 | socket.close();
|
79 | }
|
80 | return this.onclose();
|
81 | };
|
82 |
|
83 | HuntingWebsocket.prototype.onopen = function(event) {};
|
84 |
|
85 | HuntingWebsocket.prototype.onreconnect = function(event) {};
|
86 |
|
87 | HuntingWebsocket.prototype.onclose = function(event) {};
|
88 |
|
89 | HuntingWebsocket.prototype.onserver = function(event) {};
|
90 |
|
91 | HuntingWebsocket.prototype.onmessage = function(event) {};
|
92 |
|
93 | HuntingWebsocket.prototype.onerror = function(event) {};
|
94 |
|
95 | return HuntingWebsocket;
|
96 |
|
97 | })();
|
98 |
|
99 | module.exports = HuntingWebsocket;
|