Connecting to an already established UNIX socket with node.js?

15,289

I was just trying to get this to work with Linux's abstract sockets and found them to be incompatible with node's net library. Instead, the following code can be used with the abstract-socket library:

const abstract_socket = require('abstract-socket');

let client = abstract_socket.connect('\0my_abstract_socket');

client.on("connect", function() {
    ... do something when you connect ...
});

client.on("data", function(data) {
    ... do stuff with the data ...
});
Share:
15,289

Related videos on Youtube

AnalogWeapon
Author by

AnalogWeapon

I work with JavaScript, HTML, and PHP. I know enough to be dangerous with things like node.js, Perl, Python, Linux, ASP.NET/VB.NET, and MySQL.

Updated on June 30, 2022

Comments

  • AnalogWeapon
    AnalogWeapon about 2 years

    I am working on a node.js application that will connect to a UNIX socket (on a Linux machine) and facilitate communication between a web page and that socket. So far, I have been able to create socket and communicate back and forth with this code in my main app.js:

    var net = require('net');
    var fs = require('fs');
    var socketPath = '/tmp/mysocket';
    
    fs.stat(socketPath, function(err) {
        if (!err) fs.unlinkSync(socketPath);
        var unixServer = net.createServer(function(localSerialConnection) {
            localSerialConnection.on('data', function(data) {
                // data is a buffer from the socket
            });
            // write to socket with localSerialConnection.write()
        });
    
    unixServer.listen(socketPath);
    });
    

    This code causes node.js to create a UNIX socket at /tmp/mysocket and I am getting good communication by testing with nc -U /tmp/mysocket on the command line. However...

    I want to establish a connection to an already existing UNIX socket from my node.js application. With my current code, if I create a socket from the command line (nc -Ul /tmp/mysocket), then run my node.js application, there is no communication between the socket and my application (The 'connect' event is not fired from node.js server object).

    Any tips on how to go about accomplishing this? My experiments with node.js function net.createSocket instead of net.createServer have so far failed and I'm not sure if that's even the right track.

  • Anubhab
    Anubhab almost 5 years
    Please follow this discussion to get a quick and basic understanding of the differences between Unix Sockets and TCP sockets. serverfault.com/questions/124517/…