You almost always want to run a ready-to-go example of the pattern you want to use first just to confirm everything seems to be in working order. Unfortunately I don't see any ready made examples in pyzmq (which is, I assume, the binding you're using) with pub/sub both in the same thread, but I have seen and run such examples in other languages so it's not a limitation of ZMQ and should be possible in your situation.
There are a couple of things you'll want to look at. Your code sample is very sparse, there's no way for anyone to diagnose what's going on from that, but here's some suggestions:
- Before trying to subscribe to a specific topic (in your case, "id1"), try subscribing to everything:
socket_recv.setsockopt(zmq.SUBSCRIBE, "")
- this will remove the possibility that you're not setting up the subscription properly.
- Along the same lines, when you do subscribe to "id1", make sure your message is either a single frame message that begins with the string "id1", or it's a multi-frame message with "id1" as the first frame.
- I assume all of this is being run in a synchronous context, which means your subscriber should finish connecting before you move on to the next line, but just make sure that's true... if you should start publishing your message before your subscriber is finished connecting, that message will be lost.
As you note, you can't bind()
twice on the same address, something useful to keep in mind. You want to think of one side of the socket pair as a "server" (which really means the constant element) and the other side as a "client" (which really means the unreliable element)... if they both are just as constant and both as reliable, pick the one that "owns" or "originates" the data (in pub/sub, this would always be the publisher) and mark that one the "server"... you want to bind()
on your server, and connect()
on your client.
All that said... as sberry noted, your proposed use case is bi-directional communication, which doesn't seem to fit pub/sub. There are many examples of doing what you want to do in the guide, specifically look at reliable request/reply patterns. Your use case is similar enough that you'll probably want to use one of those as a base, and there is python code linked throughout the descriptions of those patterns that will help you understand which code is doing what.