-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWebSocketClient.js
More file actions
86 lines (85 loc) · 1.89 KB
/
WebSocketClient.js
File metadata and controls
86 lines (85 loc) · 1.89 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class WebSocketClient {
async connect(path, host, port, secure) {
if (host == null) {
const url = document.location.toString().match(
/(http(s?)):\/\/([^:^\/]+)(:([0-9]+))\//,
);
secure = url[1] == "https";
host = url[3];
port = url[5] ? parseInt(url[5]) : 0;
}
return new Promise((resolve) => {
const ws = new WebSocket(
(secure ? "wss" : "ws") + "://" + host + (port ? ":" + port : "") +
path,
);
ws.onopen = () => {
this.ws = ws;
resolve(this);
};
const queue = [];
ws.getSync = async () => {
if (queue.length > 0) {
return queue.shift();
}
return new Promise((resolve) => {
ws.onmessage2 = () => {
resolve(queue.shift());
ws.onmessage2 = null;
};
});
};
ws.onmessage = (mes) => {
queue.push(mes);
if (ws.onmessage2) {
ws.onmessage2();
}
};
ws.closeSync = async () => {
const res = new Promise((resolve2) => {
ws.onclose2 = () => {
resolve2();
ws.onclose2 = null;
};
});
ws.close();
return res;
};
ws.onclose = () => {
if (ws.onclose2) {
ws.onclose2();
}
this.ws = null;
};
ws.onerror = () => {
this.ws = null;
};
});
}
isConnected() {
return this.ws != null;
}
send(json) {
if (this.ws) {
try {
this.ws.send(JSON.stringify(json));
return true;
} catch (e) {
//console.log(e);
}
}
return false;
}
async get() {
if (this.ws) {
const data = await this.ws.getSync();
return JSON.parse(data.data);
}
return null;
}
async close() {
await this.ws.closeSync();
this.ws = null;
}
}
export { WebSocketClient };