-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (70 loc) · 2.4 KB
/
index.js
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
const EventEmitter = require('events');
class SocketTransport extends EventEmitter {
constructor(socket) {
super();
let buf = '';
let length = 0;
let readable, i, json, message;
let fail = null;
this.onData = chunk => {
buf += chunk;
if (buf.length > SocketTransport.MAX_BUF_LENGTH)
return socket.destroy(new Error('buffer overflow'));
readable = true;
while (readable) {
readable = false;
if (!length) {
i = buf.indexOf('#');
if (i != -1) {
length = parseInt(buf.substring(0, i));
if (isNaN(length) || length <= 0 || length > SocketTransport.MAX_BUF_LENGTH)
return socket.destroy(new Error('invalid length'));
buf = buf.substring(i + 1);
}
}
if (length && buf.length >= length) {
json = buf.slice(0, length);
buf = buf.slice(length);
length = 0;
try {
message = JSON.parse(json);
} catch (err) {
return socket.destroy(err);
}
this.emit('message', message);
readable = true;
}
}
};
this.onError = err => fail = err;
this.onClose = () => {
this.open = false;
this.emit('close', fail);
};
socket.setEncoding('utf8');
socket.setNoDelay(true);
socket.on('data', this.onData);
socket.on('error', this.onError);
socket.on('close', this.onClose);
this.socket = socket;
this.open = true;
}
detach() {
const socket = this.socket;
socket.removeListener('data', this.onData);
socket.removeListener('error', this.onError);
socket.removeListener('close', this.onClose);
this.socket = null;
return socket;
}
send(message, callback) {
const json = JSON.stringify(message);
this.socket.write(json.length + '#' + json, 'utf8', callback);
}
close() {
this.open = false;
this.socket.destroy();
}
}
SocketTransport.MAX_BUF_LENGTH = 65536;
module.exports = SocketTransport;