首先我的代码(主要来自ZMQ doc http://zguide.zeromq.org/py:mtserver):
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(12)
socket.send("hello")
socket.send("hello")
print socket.recv()
print socket.recv()
socket.close()
def workerRoutine(context):
socket = context.socket(zmq.REP)
socket.connect(SOCKET_NAME)
s = socket.recv()
print 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()
我用inproc和tcp套接字尝试过这段代码。
答案 0 :(得分: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 socket.recv()
print socket.recv()
socket.close()
def workerRoutine(context):
socket = context.socket(zmq.REP)
socket.connect(SOCKET_NAME)
s = socket.recv()
print 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()