NodeJS – UNIX Domain Sockets

Date: 2016-06-28
var net = require('net');
var socket = '/tmp/echo.sock';

var fs = require('fs');
fs.unlink(socket, function(err, result) {}); // remove a existing socket file

var connect = function(socket) {
    socket.on('end', function() {
        // exec'd when socket other end of connection sends FIN packet
        console.log('[socket on end]');
    });
    socket.on('data', function(data) {
        // data is a Buffer object
        console.log('[socket on data]', data.toString());
    });
    socket.on('end', function() {
        // emitted when the other end sends a FIN packet
    });

    socket.on('timeout', function() {
        console.log('socket', 'timeout');
    });

    socket.on('drain', function() {
        // emitted when the write buffer becomes empty
        console.log('[socket on drain]');
    });
    socket.on('error', function() {
        console.log('socket', 'error');
    });
    socket.on('close', function() {
        console.log('socket', 'close');
    });
    socket.pipe(socket);
};

var server = net.createServer(connect);
server.listen(socket, function() {
    fs.chmodSync(socket, '766');
});

server.on('listening', function() {
    var ad = server.address();
    if (typeof ad === 'string') {
        console.log('[server on listening] %s', ad);
    } else {
        console.log('[server on listening] %s:%s using %s', ad.address, ad.port, ad.family);
    }
});

server.on('connection', function(socket) {
    server.getConnections(function(err, count) {
        console.log('%d open connections!', count);
    });
});

server.on('close', function() {
    console.log('[server on close]');
});
server.on('err', function(err) {
    console.log(err);
    server.close(function() {
        console.log("shutting down the server!");
    });
});

var net = require('net');
var socket = "/tmp/echo.sock";

var client = net.createConnection(socket);

client.on("connect", function() {
    client.write('hello!');
});

client.on("data", function(data) {
    console.log("returned", data.toString());
    client.destroy();
});


client.on('close', function() {
    console.log('Connection closed');
});
3290cookie-checkNodeJS – UNIX Domain Sockets