Little socket services

Naturally in the past whenever I needed to interact with a long running process, whether it be an API or other such daemon, I've always built some sort of http api off the back of it. This usually involves at least one framework to handle http for me, not to mention having to document the api so people know how to use it. But really, for these cases the solution is much simpler. TCP. It's nothing new, but this is a great alternative to building front ends and rest api's. I first saw this done by etsy in statsd and thought this was such a good idea. A management socket can be implemented in any language, it's just a tcp socket! Here's an example in node:

const net = require('net');

function start(config, on_data_callback, on_error_callback) {
    const server = net.createServer(function (stream) {
        stream.setEncoding('ascii');

        stream.on('data', function (data) {
            const cmdline = data.trim().split(" ");
            const cmd = cmdline.shift();
            on_data_callback(cmd, cmdline, stream);
        });

        stream.on('error', function (err) {
            on_error_callback(err, stream);
        });

    });

    server.listen(config.mgmt_port || 8123, config.mgmt_host || void 0);

    return true;
};

You can wrap this up in a simple package and reuse it in all of your apps. Each application only then needs to call the start function passing in a config and a couple of callbacks. The config is obvious (port and host, which are optional). The bulk of the functionality happens in the on_data_callback, and it's that which we are interested in:

start(config, function (cmd, parameters, stream) {
    switch (cmd) {
        case 'help':
            stream.write('Commands: help status\n');
            break;
        case 'status':
            const callTime = Date.now();
            stream.write(`Uptime ${callTime - initialTime}\n`);
            break;
    }
}, function(err, stream) { /* handle errors */ });

Pretty simple really, but again - Really powerful, it means we can send commands to this app using any tcp client.

netcat (nc)

$ echo "help" | nc localhost 8123
Commands: help status

telnet

$ telnet localhost 8123
> help
Commands: help status

Worth remembering.