This repository has been archived by the owner on Jul 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.js
63 lines (54 loc) · 1.65 KB
/
websocket.js
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
52
53
54
55
56
57
58
59
60
61
62
63
const WebSocket = require('ws');
const pako = require('pako');
class IIRoseWebSocket {
constructor() {
this.open();
setInterval(() => {
if (this.websocket.readyState === WebSocket.OPEN) {
this.send('u');
}
}, 36e4);
}
open() {
this.websocket = new WebSocket('wss://m.iirose.com/', {
rejectUnauthorized: false,
});
this.websocket.binaryType = 'arraybuffer';
this.setCallBacks();
}
setCallBacks() {
this.websocket.onopen = () => this.onopen();
this.websocket.onmessage = event => {
let array = new Uint8Array(event.data);
let message;
if (array[0] === 1) {
message = pako.inflate(array.slice(1), {
to: 'string'
});
} else {
message = Buffer.from(array).toString('utf8');
}
this.onmessage(message);
};
this.websocket.onclose = () => this.open();
}
close() {
if (this.websocket.readyState === WebSocket.OPEN) {
this.websocket.terminate();
}
}
send(data) {
let buffer = Buffer.from(data);
let array = Uint8Array.from(buffer);
if (array.size > 256) {
let deflatedData = pako.gzip(data);
let deflatedArray = new Uint8Array(deflatedData.length + 1);
deflatedArray[0] = 1;
deflatedArray.set(deflatedData, 1);
this.websocket.send(deflatedArray);
} else {
this.websocket.send(array);
}
}
}
module.exports = new IIRoseWebSocket();