forked from craftbeerpi/craftbeerpi4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
samples.txt
51 lines (38 loc) · 954 Bytes
/
samples.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function noop() {}
export default function (url, opts) {
opts = opts || {};
var ws, num=0, $={};
var max = opts.maxAttempts || Infinity;
$.open = function () {
ws = new WebSocket(url, opts.protocols || []);
ws.onmessage = opts.onmessage || noop;
ws.onopen = function (e) {
(opts.onopen || noop)(e);
num = 0;
};
ws.onclose = function (e) {
e.code === 1e3 || e.code === 1005 || $.reconnect(e);
(opts.onclose || noop)(e);
};
ws.onerror = function (e) {
(e && e.code==='ECONNREFUSED') ? $.reconnect(e) : (opts.onerror || noop)(e);
};
};
$.reconnect = function (e) {
(num++ < max) ? setTimeout(function () {
(opts.onreconnect || noop)(e);
$.open();
}, opts.timeout || 1e3) : (opts.onmaximum || noop)(e);
};
$.json = function (x) {
ws.send(JSON.stringify(x));
};
$.send = function (x) {
ws.send(x);
};
$.close = function (x, y) {
ws.close(x || 1e3, y);
};
$.open(); // init
return $;
}