This repository has been archived by the owner on Jun 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsocket.ts
93 lines (77 loc) · 2.22 KB
/
socket.ts
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
87
88
89
90
91
92
93
import * as protocol from 'voxelsrv-protocol';
import type WebSocket from 'ws';
export class BaseSocket {
socket: any;
listeners: { [i: string]: { callback: (data: any) => void; remove: boolean }[] } = {};
debugListener: (sender: string, type: string, data: object) => void = (sender, type, data) => {};
ip: string = '0.0.0.0';
constructor(ip: string) {
this.ip = ip;
}
send(type: string, data: Object) {
const packet = protocol.parseToMessage('server', type, data);
if (packet != null) {
this.socket.send(packet);
this.debugListener('server', type, data);
}
}
close() {
this.emit('close', true);
this.listeners = {};
}
protected emit(type, data) {
this.debugListener('client', type, data);
if (this.listeners[type] != undefined) {
this.listeners[type] = this.listeners[type].filter((event) => {
event.callback(data);
return !event.remove;
});
}
}
on(type: string, func: (data: any) => void) {
if (this.listeners[type] != undefined) {
this.listeners[type].push({ callback: func, remove: false });
} else {
this.listeners[type] = new Array();
this.listeners[type].push({ callback: func, remove: false });
}
}
once(type: string, func: (data: any) => void) {
if (this.listeners[type] != undefined) {
this.listeners[type].push({ callback: func, remove: true });
} else {
this.listeners[type] = new Array();
this.listeners[type].push({ callback: func, remove: true });
}
}
}
export class WSSocket extends BaseSocket {
constructor(socket: WebSocket, ip: string) {
super(ip);
this.socket = socket;
this.socket.binaryType = 'arraybuffer';
this.socket.onopen = () => {
this.emit('connection', {});
};
this.socket.on('error', () => {
this.emit('error', { reason: `Connection error!` });
});
this.socket.on('close', () => {
this.emit('close', { reason: `Connection closed!` });
});
this.socket.on('message', (m: ArrayBuffer) => {
try {
const packet = protocol.parseToObject('client', new Uint8Array(m));
if (packet != null) this.emit(packet.type, packet.data);
} catch (e) {
console.error('Invalid message', e);
socket.close();
}
});
}
close() {
this.emit('close', true);
this.listeners = {};
this.socket.close();
}
}