-
Notifications
You must be signed in to change notification settings - Fork 1
/
ServerSync.js
47 lines (45 loc) · 951 Bytes
/
ServerSync.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
import { Server } from "./Server.js";
class WebSocketServer {
constructor(server, sockid) {
this.server = server;
this.sockid = sockid;
this.resolvefunc = null;
}
async get() {
return new Promise((resolve) => {
this.resolvefunc = resolve;
});
}
send(json) {
this.server.send(this.sockid, json);
}
close() {
this.server.close(this.sockid);
}
}
class ServerSync extends Server {
constructor(port, callback) {
super(port);
this.callback = callback;
this.wss = {};
}
async onopen(sockid) {
const ws = new WebSocketServer(this, sockid);
this.wss[sockid] = ws;
await this.callback(ws);
ws.close();
}
onclose(sockid) {
delete this.wss[sockid];
}
onmessage(sockid, req) {
const ws = this.wss[sockid];
if (ws) {
if (ws.resolvefunc) {
ws.resolvefunc(req);
}
}
return null; // { reply: "ok", req };
}
}
export { ServerSync };