Socket is busy when connecting before bind

I'm using zeromq to push messages from node.js server to my worker. I create a router socket on the node.js side

var sender = zmq.socket('router');
sender.bind('tcp://127.0.0.1:6633', function(err) {
  if (err) {
    console.log( 'Error binding socket' );
    return;
  }
  console.log('OK!');
}

and connect to this address with a dealer in the worker code.

The problem occurs when the worker connects first, before bind (not always, but very often). This should not be a problem regarding the zeromq documentation, so I think it's a problem in the node.js binding, the question is how can I solve this?

Also a problem that I can catch this exception Socket is busy in process.on('uncaughtException',...), not in the bind function

I should mention that I'm doing this on windows 7 64bit.

The problem is probably that you are using bind() where you should in fact be using bindSync(). When you read the sources, you discover that the async bind() in fact locks the socket and checks the lock every time you do anything with it. What you are probably experiencing is that a worker connects before the socket is unlocked and so it throws an exception. Just replacing bind() with bindSync() worked for me. That is, however, not an idea solution I guess, or rather not very node.js-ish. Let's demonstrate what I mean:

var zmq = require('zmq')
  , sender;
sender = zmq.socket('router');
sender.bind('tcp://127.0.0.1:6633', function(err) {
  if (err) {
    console.log( 'Error binding socket' );
    return;
  }
  sender.close(); // This is fine! The socket is ready!
});

sender.close(); // This is wrong! The socket is not ready yet!

So you can either call bindSync() and don't care, or call bind() and continue the work in the callback, but you definitely can't use bind() and continue without waiting for it to finish. bindSync() makes the code simpler to read, but you block the whole node.js instance during the call. So I think that the bind() way is more clean in a way that node.js should be used...

Hope this helped ;-)