/
server.ts
128 lines (109 loc) · 3.65 KB
/
server.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { asyncOperation, ParsedHost, parseHost } from '@deepkit/core';
import { RpcKernel } from '@deepkit/rpc';
import { existsSync, unlinkSync } from 'fs';
import { createServer, Server, Socket } from 'net';
/**
* Uses the node `net` module to create a server. Supports unix sockets.
*/
export class RpcTcpServer {
protected server?: Server;
protected host: ParsedHost;
constructor(
protected kernel: RpcKernel,
host: string
) {
this.host = parseHost(host);
if (this.host.isUnixSocket && existsSync(this.host.unixSocket)) {
unlinkSync(this.host.unixSocket);
}
}
start() {
return asyncOperation((resolve, reject) => {
this.server = createServer();
this.server.on('listening', () => {
resolve(true);
});
this.server.on('error', (err: any) => {
reject(new Error('Could not start broker server: ' + err));
});
this.server.on('connection', (socket: Socket) => {
const connection = this.kernel?.createConnection({
write(b: Uint8Array) {
socket.write(b);
},
clientAddress(): string {
return socket.remoteAddress || '';
},
close() {
socket.destroy();
},
bufferedAmount(): number {
return socket.writableLength || 0;
}
});
socket.on('data', (data: Uint8Array) => {
connection!.feed(data);
});
socket.on('close', () => {
connection!.close();
});
socket.on('error', () => {
connection!.close();
});
});
if (this.host.isUnixSocket) {
this.server.listen(this.host.unixSocket);
} else {
this.server.listen(this.host.port || 8811, this.host.host);
}
});
}
close() {
this.server?.close();
}
}
import ws from 'ws';
import type { ServerOptions as WebSocketServerOptions } from 'ws';
import { IncomingMessage } from 'http';
export class RpcWebSocketServer {
protected server?: ws.Server;
protected host: ParsedHost;
constructor(
protected kernel: RpcKernel,
host: string
) {
this.host = parseHost(host);
if (this.host.isUnixSocket && existsSync(this.host.unixSocket)) {
unlinkSync(this.host.unixSocket);
}
}
close() {
this.server?.close();
}
start(options: WebSocketServerOptions): void {
const defaultOptions = { host: this.host.host, port: this.host.port };
this.server = new ws.Server({ ...defaultOptions, ...options });
this.server.on('connection', (ws, req: IncomingMessage) => {
const connection = this.kernel?.createConnection({
write(b) {
ws.send(b);
},
close() {
ws.close();
},
bufferedAmount(): number {
return ws.bufferedAmount;
},
clientAddress(): string {
return req.socket.remoteAddress || '';
}
});
ws.on('message', async (message: Uint8Array) => {
connection.feed(message);
});
ws.on('close', async () => {
connection.close();
});
});
}
}