-
Notifications
You must be signed in to change notification settings - Fork 1
/
remote-process-client.js
112 lines (96 loc) · 2.63 KB
/
remote-process-client.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
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
/**
* Created by Quake on 18.12.2018
*/
'use strict';
const Game = require('./model/Game');
const Action = require('./model/Action');
const Rules = require('./model/Rules');
let client = null;
let strBuffer = [];
module.exports.connect = function connect(host, port, onConnect) {
const net = require('net');
var request = [];
var busy;
client = net.connect(port, host, function connectHandler() {
// 'connect' listener
console.log('connected to server!');
writeline("json");
onConnect();
});
client.setNoDelay();
client.on('data', dataHandler);
client.on('error', function onError(e) {
console.log("SOCKET ERROR: " + e.message);
process.exit(1);
});
client.on('close', function onClose() {
console.log('server closed connection.');
client.unref();
process.exit();
});
client.on('end', function onEnd() {
console.log('disconnected from server');
process.exit();
});
let tickData = '';
function dataHandler(data) {
busy = true;
if (data) {
// sometimes we get tick data by parts
tickData = tickData + data.toString();
// tickData is complete when we get '\n'
if (tickData[tickData.length -1] === '\n') {
strBuffer.push(tickData);
tickData = '';
}
}
while (request.length && strBuffer.length) {
let cb = request.shift();
let data = strBuffer.shift();
cb(data);
}
busy = false;
}
function readline() {
return strBuffer.shift();
}
function writeline(line) {
line += "\n";
client.write(line);
}
function readSequence(cb) {
if (!cb) {
throw 'Callback expected';
}
request.push(cb);
if (!busy) {
dataHandler();
}
}
this.readRules = function(cb) {
readSequence(function(data) {
let rules = new Rules();
rules.read(data);
cb(rules);
});
}
this.readGame = function(cb) {
readSequence(function(data) {
let game = new Game();
game.read(data);
cb(game);
});
}
this.write = function(actions) {
let map = {};
for (let id in actions) {
map[id] = actions[id].toObject();
}
let json = JSON.stringify(map);
writeline(json);
}
this.writeTokenMessage = function(token, cb) {
writeline(token);
cb();
}
}