discord-rpc/test-rpc-server/rpc-server.js

62 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-06-27 21:23:09 +02:00
const net = require('net');
const repl = require('repl');
const {PipePath, RpcMessage} = require('./rpc-message');
2017-06-27 21:23:09 +02:00
let connectionNonce = 0;
global.connections = {};
2017-06-27 21:23:09 +02:00
const server = net.createServer(function(sock) {
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
sock.on('data', function(data) {
messages++;
2017-06-27 21:23:09 +02:00
const msgObj = RpcMessage.deserialize(data);
if (msgObj != null) {
const {opcode, data} = msgObj;
console.log(`\nServer (${myConnection}): got opcode: ${opcode}, data: ${JSON.stringify(data)}`);
2017-06-27 21:23:09 +02:00
}
else {
console.log('\nServer: got some data', data.toString());
2017-06-27 21:23:09 +02:00
}
});
sock.on('end', function() {
delete global.connections[myConnection];
console.log('\nServer: on end', myConnection);
2017-06-27 21:23:09 +02:00
});
});
server.on('close', function(){
console.log('\nServer: on close');
});
2017-06-27 21:23:09 +02:00
try {
server.listen(PipePath, function(){
console.log('\nServer: on listening');
2017-06-27 21:23:09 +02:00
});
} catch(e) {
console.error('\nServer: could not start:', e);
}
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);
sock.write(RpcMessage.sendClose(123, 'killed'));
2017-07-10 23:54:58 +02:00
sock.destroy();
}
this.displayPrompt();
}
});
2017-07-10 23:54:58 +02:00