我在 ZMQ 中设置了一个 REP/DEALER 连接,发现当 REP 向 DEALER 发送一条消息时,后者必须接收两次才能获取消息。为什么是这样?
复制此代码的代码是此 SO answer中代码的修改版本。他们的代码每个工人只收到一次,但我对此进行了测试,我只得到了一个“世界”。我必须收到四次才能获得 2 个“世界”,例如:
import zmq
import time
import sys
import threading
SOCKET_NAME = "tcp://127.0.0.1:8000"
#SOCKET_NAME = "inproc://mysocket"
def dealerRoutine(context):
socket = context.socket(zmq.DEALER)
socket.bind(SOCKET_NAME)
time.sleep(1)
socket.send("", zmq.SNDMORE)
socket.send("hello")
socket.send("", zmq.SNDMORE)
socket.send("hello")
print "first msg", socket.recv()
print "second msg", socket.recv()
print "third msg", socket.recv()
print "fourth msg", socket.recv()
socket.close()
def workerRoutine(context):
socket = context.socket(zmq.REP)
socket.connect(SOCKET_NAME)
s = socket.recv()
print "worker received", s
socket.send("world")
context = zmq.Context()
workers = []
for i in range(0, 2):
worker = threading.Thread(target=workerRoutine, args=([context]))
workers.append(worker)
worker.start()
dealerRoutine(context)
for worker in workers:
worker.terminated = True
context.term()