forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient-tcp.ts
More file actions
81 lines (72 loc) · 2.35 KB
/
Copy pathclient-tcp.ts
File metadata and controls
81 lines (72 loc) · 2.35 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
import * as net from 'net';
import * as JsonSocket from 'json-socket';
import { ClientProxy } from './client-proxy';
import { ClientMetadata } from '../interfaces/client-metadata.interface';
import { Logger } from '@nestjs/common';
const DEFAULT_PORT = 3000;
const DEFAULT_HOST = 'localhost';
const CONNECT_EVENT = 'connect';
const MESSAGE_EVENT = 'message';
const ERROR_EVENT = 'error';
const CLOSE_EVENT = 'close';
export class ClientTCP extends ClientProxy {
private readonly logger = new Logger(ClientTCP.name);
private readonly port: number;
private readonly host: string;
private isConnected = false;
private socket;
constructor({ port, host }: ClientMetadata) {
super();
this.port = port || DEFAULT_PORT;
this.host = host || DEFAULT_HOST;
}
public init(): Promise<{}> {
this.socket = this.createSocket();
return new Promise((resolve) => {
this.socket.on(CONNECT_EVENT, () => {
this.isConnected = true;
this.bindEvents(this.socket);
resolve(this.socket);
});
this.socket.connect(this.port, this.host);
});
}
protected async sendSingleMessage(msg, callback: (...args) => any) {
const sendMessage = (socket) => {
socket.sendMessage(msg);
socket.on(MESSAGE_EVENT, (buffer) => this.handleResponse(socket, callback, buffer));
};
if (this.isConnected) {
sendMessage(this.socket);
return Promise.resolve();
}
const socket = await this.init();
sendMessage(socket);
}
public handleResponse(socket, callback: (...args) => any, buffer) {
const { err, response, disposed } = buffer;
if (disposed) {
callback(null, null, true);
socket.end();
return;
}
callback(err, response);
}
public createSocket() {
return new JsonSocket(new net.Socket());
}
public close() {
if (this.socket) {
this.socket.end();
this.isConnected = false;
this.socket = null;
}
}
public bindEvents(socket) {
socket.on(ERROR_EVENT, (err) => this.logger.error(err));
socket.on(CLOSE_EVENT, () => {
this.isConnected = false;
this.socket = null;
});
}
}