sub
频道不一定是要绑定的频道,因此您可以让订阅者绑定,并且每个子pub
频道都可以连接到该频道并发送他们的消息。在这种特殊情况下,我认为该multiprocessing
模块更适合,但我认为它值得一提:
import zmq
import threading
# So that you can copy-and-paste this into an interactive session, I'm
# using threading, but obviously that's not what you'd use
# I'm the subscriber that multiple clients are writing to
def parent():
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, 'Child:')
# Even though I'm the subscriber, I'm allowed to get this party
# started with `bind`
socket.bind('tcp://127.0.0.1:5000')
# I expect 50 messages
for i in range(50):
print 'Parent received: %s' % socket.recv()
# I'm a child publisher
def child(number):
context = zmq.Context()
socket = context.socket(zmq.PUB)
# And even though I'm the publisher, I can do the connecting rather
# than the binding
socket.connect('tcp://127.0.0.1:5000')
for data in range(5):
socket.send('Child: %i %i' % (number, data))
socket.close()
threads = [threading.Thread(target=parent)] + [threading.Thread(target=child, args=(i,)) for i in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
特别是,文档的核心消息传递模式部分讨论了对于模式,任何一方都可以绑定(和另一方连接)的事实。