I'm using a PUB
/SUB
design and my question is:
Can I .bind()
to a port after another socket has .connect()
-ed to it,
or should I .bind()
before another socket tries to .connect()
to the same address?
In other words:
Does the order of .bind()
and .connect()
matter?
( I think this question is not specific to PUB
/SUB
but is relevant for any design ).
A driving principle behind ZMQ is not worrying whether the socket you're trying to connect to is already there or not. These are details that ZMQ tries to abstract away from you, the developer. So, no, the order of bind()
and connect()
does not matter for any socket type.
I suggest you read the zmq guide if you plan to do extensive work with it, relevant portion here:
Remember that ZeroMQ does asynchronous I/O, i.e., in the background. Say you have two nodes doing this, in this order:
- Subscriber connects to an endpoint and receives and counts messages.
- Publisher binds to an endpoint and immediately sends 1,000 messages.
Then the subscriber will most likely not receive anything. You'll blink, check that you set a correct filter and try again, and the subscriber will still not receive anything.
... there's an important point to note here, for PUB/SUB - even if you connect()
first with your subscriber, that connection doesn't actually occur until after the publisher has bind()
-ed, so if you attempt to send messages with your publisher without waiting for your subscriber to finish its connection, those messages will never make it to your subscriber.