forked from lsongdev/node-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp.js
More file actions
34 lines (30 loc) · 835 Bytes
/
tcp.js
File metadata and controls
34 lines (30 loc) · 835 Bytes
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
const tcp = require('net');
const Packet = require('../packet');
class Server extends tcp.Server {
constructor(options) {
super();
if (typeof options === 'function') {
this.on('request', options);
}
this.on('connection', this.handle.bind(this));
}
async handle(client) {
try {
const data = await Packet.readStream(client);
const message = Packet.parse(data);
this.emit('request', message, this.response.bind(this, client), client);
} catch (e) {
this.emit('requestError', e);
client.destroy();
}
}
response(client, message) {
if (message instanceof Packet) {
message = message.toBuffer();
}
const len = Buffer.alloc(2);
len.writeUInt16BE(message.length);
client.end(Buffer.concat([ len, message ]));
}
}
module.exports = Server;