/
client.ts
54 lines (47 loc) · 1.51 KB
/
client.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
import { ParsedHost, parseHost } from '@deepkit/core';
import { ClientTransportAdapter, TransportConnectionHooks } from '@deepkit/rpc';
import { connect } from 'net';
/*
* Uses the node `net` module to connect. Supports unix sockets.
*/
export class RpcTcpClientAdapter implements ClientTransportAdapter {
protected host;
constructor(
host: string
) {
this.host = parseHost(host);
}
public async connect(connection: TransportConnectionHooks) {
const port = this.host.port || 8811;
const socket = this.host.isUnixSocket ? connect({ path: this.host.unixSocket }) : connect({
port: port,
host: this.host.host
});
socket.on('data', (data: Uint8Array) => {
connection.onData(data);
});
socket.on('close', () => {
connection.onClose();
});
socket.on('error', (error: any) => {
connection.onError(error);
});
socket.on('connect', async () => {
connection.onConnected({
clientAddress: () => {
return this.host.toString();
},
bufferedAmount(): number {
//implement that to step back when too big
return socket.bufferSize;
},
close() {
socket.end();
},
send(message) {
socket.write(message);
}
});
});
}
}