本文介绍了多线程和 ZMQ DEALER/REP hello world 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先是我的代码(主要来自 ZMQ doc http://zguide.zeromq.org/py:mtserver):
First of all my code (largely inspired from 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 套接字尝试过这段代码.
I've tried this code with both inproc and tcp sockets.
- inproc 在工作人员尝试连接时出错
- TCP 只在经销商发送后等待,没有工人打印,经销商没有收到其他消息
- 我已经考虑了慢连接器问题并添加了一个睡眠(一个在工作人员连接之前,一个在经销商的 send() 之前):这只会导致 inproc 的行为与 TCP 相同.
PS:我很抱歉驼峰,但我已经沉迷于它了.
PS : I'm sorry for camelCase but I'm addicted to it.
推荐答案
我通过:
- 对于经销商,分多部分发送您的消息,第一部分是空消息,第二部分是您的消息
- 减少了计时器(虽然没有帮助)
代码如下:
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()
这篇关于多线程和 ZMQ DEALER/REP hello world 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!