forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp-socket.ts
More file actions
78 lines (66 loc) · 1.94 KB
/
Copy pathtcp-socket.ts
File metadata and controls
78 lines (66 loc) · 1.94 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
import { Buffer } from 'buffer';
import { Socket } from 'net';
import {
CLOSE_EVENT,
CONNECT_EVENT,
DATA_EVENT,
ERROR_EVENT,
MESSAGE_EVENT,
} from '../constants';
import { NetSocketClosedException } from '../errors/net-socket-closed.exception';
import { InvalidJSONFormatException } from '../errors/invalid-json-format.exception';
export abstract class TcpSocket {
private isClosed = false;
public get netSocket() {
return this.socket;
}
constructor(public readonly socket: Socket) {
this.socket.on(DATA_EVENT, this.onData.bind(this));
this.socket.on(CONNECT_EVENT, () => (this.isClosed = false));
this.socket.on(CLOSE_EVENT, () => (this.isClosed = true));
this.socket.on(ERROR_EVENT, () => (this.isClosed = true));
}
public connect(port: number, host: string) {
this.socket.connect(port, host);
return this;
}
public on(event: string, callback: (err?: any) => void) {
this.socket.on(event, callback);
return this;
}
public once(event: string, callback: (err?: any) => void) {
this.socket.once(event, callback);
return this;
}
public end() {
this.socket.end();
return this;
}
public sendMessage(message: any, callback?: (err?: any) => void) {
if (this.isClosed) {
callback && callback(new NetSocketClosedException());
return;
}
this.handleSend(message, callback);
}
protected abstract handleSend(message: any, callback?: (err?: any) => void);
private onData(data: Buffer) {
try {
this.handleData(data);
} catch (e) {
this.socket.emit(ERROR_EVENT, e.message);
this.socket.end();
}
}
protected abstract handleData(data: Buffer | string);
protected emitMessage(data: string) {
let message: Record<string, unknown>;
try {
message = JSON.parse(data);
} catch (e) {
throw new InvalidJSONFormatException(e, data);
}
message = message || {};
this.socket.emit(MESSAGE_EVENT, message);
}
}