-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNESTrisServer.js
More file actions
78 lines (58 loc) · 1.8 KB
/
NESTrisServer.js
File metadata and controls
78 lines (58 loc) · 1.8 KB
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
const fs = require('fs');
const net = require('net');
const EventEmitter = require('events');
class NESTrisServer extends EventEmitter {
constructor(port, server_id = 'default', log_frames=null) {
super();
this.port = port;
this.server_id = server_id;
if (log_frames) {
this.wstream = fs.createWriteStream(log_frames);
}
this.server = net.createServer(this.handleConnection.bind(this));
this.server.on('error', console.error);
this.server.listen(port, () => {
console.log(`Server ${this.server_id} ready`);
});
}
clearConn() {
if (this.conn) {
this.conn.removeAllListeners();
this.conn.end();
}
}
handleConnection(conn) {
console.log(`OCR producer ${this.server_id} connected`);
this.clearConn(); // incoming connection kicks old one out... TODO: IMplement safeguard to be be controlled by API
this.conn = conn;
let stream_data = Buffer.from([]);
const onData = () => {
// check if ready to process:
const msg_length = stream_data.readInt32LE();
if (stream_data.length < msg_length + 4) return; // not enough data, wait for more
const frame_data = stream_data.toString('utf8', 4, msg_length + 4)
if (this.wstream) {
this.wstream.write(`${frame_data}\n`);
}
this.emit('frame', JSON.parse(frame_data));
stream_data = stream_data.slice(msg_length + 4);
if (stream_data.length) {
// there's more data, check if we can process some more!
onData();
}
}
conn
.on('error', (err) => {
console.log(`OCR producer ${this.server_id} error ${err.errno || err.code}`);
})
.on('close', () => {
console.log(`OCR producer ${this.server_id} disconnected`);
conn.removeAllListeners();
})
.on('data', data => {
stream_data = Buffer.concat([stream_data, data]);
onData();
});
}
}
module.exports = NESTrisServer;