-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.ts
46 lines (37 loc) · 1.3 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
import * as childProcess from 'child_process';
import * as net from 'net';
import {ChunkParser, ChunkSerializer} from './chunk';
import {Ref} from './command';
import {Handler} from './handler';
import {CommandFactory} from './commandfactory';
export abstract class BaseServer {
private readonly handler: Handler;
constructor(commandFactory: CommandFactory, ref: Ref) {
this.handler = new Handler(commandFactory, ref);
}
protected connection(socket: net.Socket) {
socket.setNoDelay(true);
socket.unref();
const parser = new ChunkParser();
const serializer = new ChunkSerializer();
socket.pipe(parser);
serializer.pipe(socket);
this.handler.handle(parser, serializer);
socket.on('error', socket.destroy);
socket.on('timeout', () => socket.destroy(new Error('timeout')));
}
status(): Promise<any> {
return Promise.resolve(this.handler.status());
}
}
export class Server extends BaseServer {
public readonly server: net.Server;
constructor(commandFactory: CommandFactory) {
const server = net.createServer({allowHalfOpen:true}, socket => this.connection(socket));
super(commandFactory, server);
this.server = server;
}
shutdown() {
this.server.close();
}
}