Unix sockets on host Js

Fast and basic node, I am working with a unix socket for server-to-server communication between a C ++ application and my NodeJs server,

I wrote a nodeJs server like this:

var net = require('net');
var unixSocketServer = net.createConnection('/tmp/unixSocket');
unixSocketServer.on('connect',function(){
    console.log('unix server socket connected on /tmp/unixSocket');
    ...
});

      

However, I am getting a communication failure error. I can understand that the C ++ app hasn't opened / connected to the socket yet. My questions are: why does it matter? shouldn't the nodeJs server wait until the "connect" event occurs? Am I using nodeJs currently? Did I miss something?

+3


source to share


1 answer


Ok, there are some misunderstandings here. Let's start with what a "unix socket" really is. I think you are thinking that it is just a file element that acts as a server on its own through the OS / filesystem. This is not entirely correct. While it is indeed linked through the filesystem, it is not a regular file. Instead, it is similar to a TCP / IP socket, except that instead of binding the IP and port, a file path is bound.

The key point is that this is just a bound socket with a different type of address (and some additional features but not in scope here). So that means something has to bind the socket! In this case, we need a server, just like we would if we were exchanging a "normal" port. If the server is not bound to a path, you will get an error, just like connecting to a port without a listener.

To create a server in a unix domain juice in node, it's pretty simple:



'use strict';

const net = require('net');
const unixSocketServer = net.createServer();

unixSocketServer.listen('/tmp/unixSocket', () => {
  console.log('now listening');
});

unixSocketServer.on('connection', (s) => {
  console.log('got connection!');
  s.write('hello world');
  s.end();
});

      

Note that there is another difference between "normal" sockets and unix domain sockets: once the server is executed with a unix domain socket, it will not be automatically destroyed. Instead, you should use unlink /tmp/unixSocket

to reuse this address / path

+1


source







All Articles