Thursday 4 May 2017

How to create a Node.js Unix socket client when server might not be available yet

I'm having trouble getting my Node.js Unix socket stood up. The Node.js code spawns a C app that acts as the server. The server might not be ready by the time I start trying to connect to it from the Node.js code, so I get an error. I even try to naively catch it, but it doesn't work. Here's a simplified version of the code:

var net = require('net');

const URI_SOCK = '/opt/tmp/.socket';

try {
  const socket = net.connect(URI_SOCK, function() {
    //'connect' listener
    console.log('Connected to socket!');
    socket.write("42");
  });
} catch(err) {
  console.log("Caught you!");
}

Here's what happens when I try to run it:

 ✘ ⚡ ⚙ root@ncooprider-tron  ~  node test.js

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

Any ideas for how to catch that error or what to do so I can force the program to wait until the server is ready to receive clients?



via Coop

No comments:

Post a Comment