SocketWrapper.ts
1.08 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
import { Socket } from "socket.io";
import { RawMessage, ServerResponse } from "../../common";
export interface SocketWrapper {
setHandler: (listener: (raw: RawMessage) => ServerResponse<any>) => void;
setDisconnectHandler: (listener: () => void) => void;
setPingHandler: (listener: () => void) => void;
send: (raw: RawMessage) => void;
sendPing: () => void;
}
export class SocketIoWrapper implements SocketWrapper {
private socketIo: Socket;
constructor(socketIo: Socket) {
this.socketIo = socketIo;
}
public setHandler(listener: (raw: RawMessage) => ServerResponse<any>): void {
this.socketIo.on("msg", (raw: RawMessage, callback: Function) => {
callback(listener(raw));
});
}
public setDisconnectHandler(listener: () => void) {
this.socketIo.on("disconnect", () => {
listener();
});
}
public setPingHandler(listener: () => void) {
this.socketIo.on("ping", () => {
listener();
});
}
public send(raw: RawMessage) {
this.socketIo.emit("msg", raw);
}
public sendPing() {
this.socketIo.emit("ping", {});
}
}