2017-06-27 21:23:09 +02:00
|
|
|
const net = require('net');
|
2017-07-08 01:00:29 +02:00
|
|
|
const repl = require('repl');
|
|
|
|
const {PipePath, RpcMessage} = require('./rpc-message');
|
2017-06-27 21:23:09 +02:00
|
|
|
|
2017-07-08 01:00:29 +02:00
|
|
|
let connectionNonce = 0;
|
|
|
|
global.connections = {};
|
2017-06-27 21:23:09 +02:00
|
|
|
|
2017-06-29 17:58:03 +02:00
|
|
|
const server = net.createServer(function(sock) {
|
2017-07-08 01:00:29 +02:00
|
|
|
connectionNonce += 1;
|
|
|
|
console.log('Server: on connection', connectionNonce);
|
|
|
|
let myConnection = connectionNonce;
|
|
|
|
let messages = 0;
|
|
|
|
|
|
|
|
global.connections[myConnection] = sock;
|
2017-06-27 21:23:09 +02:00
|
|
|
|
2017-06-29 17:58:03 +02:00
|
|
|
sock.on('data', function(data) {
|
2017-07-08 01:00:29 +02:00
|
|
|
messages++;
|
2017-06-27 21:23:09 +02:00
|
|
|
const msgObj = RpcMessage.deserialize(data);
|
|
|
|
if (msgObj != null) {
|
2017-07-08 01:00:29 +02:00
|
|
|
const {opcode, data} = msgObj;
|
|
|
|
console.log(`\nServer (${myConnection}): got opcode: ${opcode}, data: ${JSON.stringify(data)}`);
|
2017-06-27 21:23:09 +02:00
|
|
|
}
|
|
|
|
else {
|
2017-07-08 01:00:29 +02:00
|
|
|
console.log('\nServer: got some data', data.toString());
|
2017-06-27 21:23:09 +02:00
|
|
|
}
|
|
|
|
});
|
2017-06-29 17:58:03 +02:00
|
|
|
|
|
|
|
sock.on('end', function() {
|
2017-07-08 01:00:29 +02:00
|
|
|
delete global.connections[myConnection];
|
|
|
|
console.log('\nServer: on end', myConnection);
|
2017-06-27 21:23:09 +02:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
server.on('close', function(){
|
2017-07-08 01:00:29 +02:00
|
|
|
console.log('\nServer: on close');
|
|
|
|
});
|
2017-06-27 21:23:09 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
server.listen(PipePath, function(){
|
2017-07-08 01:00:29 +02:00
|
|
|
console.log('\nServer: on listening');
|
2017-06-27 21:23:09 +02:00
|
|
|
});
|
|
|
|
} catch(e) {
|
2017-07-08 01:00:29 +02:00
|
|
|
console.error('\nServer: could not start:', e);
|
2017-06-29 17:58:03 +02:00
|
|
|
}
|
2017-07-08 01:00:29 +02:00
|
|
|
|
|
|
|
const replServer = repl.start({prompt: '> ', useGlobal: true, breakEvalOnSigint: true});
|
|
|
|
replServer.defineCommand('kill', {
|
|
|
|
help: 'Kill a client',
|
|
|
|
action(who) {
|
|
|
|
this.bufferedCommand = '';
|
|
|
|
who = parseInt(who, 10);
|
|
|
|
const sock = global.connections[who];
|
|
|
|
if (sock) {
|
2017-07-10 23:54:58 +02:00
|
|
|
console.log('killing', who);
|
2017-07-08 01:00:29 +02:00
|
|
|
sock.write(RpcMessage.sendClose(123, 'killed'));
|
2017-07-10 23:54:58 +02:00
|
|
|
sock.destroy();
|
2017-07-08 01:00:29 +02:00
|
|
|
}
|
|
|
|
this.displayPrompt();
|
|
|
|
}
|
|
|
|
});
|
2017-07-10 23:54:58 +02:00
|
|
|
|