我有一个发布服务器的代码,它实例化一些类实例并发布一些消息。
但是,我在订阅方没有收到任何内容。
发布商
import zmq
import time
from multiprocessing import Process
class SendData:
def __init__(self, msg, port):
self.msg = msg
self.port = port
ctx = zmq.Context()
self.sock = ctx.socket(zmq.PUB)
self.sock.bind('tcp://127.0.0.1:'+str(self.port))
time.sleep(1)
def sender(self):
self.sock.send_json(self.msg)
def main():
for device, port in zip(['2.2.2.2', '5.5.5.5'],[5001, 5002]):
msg = {device:'Some random message'}
instance = SendData(device, port)
Process(target=instance.sender).start()
if __name__ == "__main__":
main()
订户
import zmq
ctx = zmq.Context()
recv_sock1 = ctx.socket(zmq.SUB)
recv_sock1.connect('tcp://127.0.0.1:5001')
recv_sock1.setsockopt(zmq.SUBSCRIBE, '')
recv_sock2 = ctx.socket(zmq.SUB)
recv_sock2.connect('tcp://127.0.0.1:5002')
recv_sock2.setsockopt(zmq.SUBSCRIBE, '')
while True:
if recv_sock1.poll(10):
msg = recv_sock1.recv_json()
print msg
if recv_sock2.poll(10):
msg = recv_sock2.recv_json()
print msg
在发布商发布任何内容之前我订阅了订阅者。此外,我可以看到TCP连接在Established中,因此建立连接。
Q1:是否支持类实例的0mq发布商? Q2:我缺少什么?
答案 0 :(得分:1)
如前所述,尝试在进程之间共享ZeroMQ上下文是问题, user3666197 的解决方案将起作用。
但是,我建议在这种情况下继承multiprocessing.Process
。这样,在哪个进程中执行代码的哪一部分就更清楚了。它还使您的代码更具可读性和可重用性。
以下代码为每台设备创建一个发件人进程。在程序运行期间可以重用发送方进程以发送更多数据:
import multiprocessing
import queue
import zmq
import time
class Sender(multiprocessing.Process):
def __init__(self, port):
super(Sender, self).__init__()
self._port = port
self._messages = multiprocessing.Queue()
self._do_stop = multiprocesing.Event()
def run(self):
"""
This code is executed in a new process.
"""
ctx = zmq.Context()
sock = ctx.socket(zmq.PUB)
sock.bind("tcp://127.0.0.1:" + str(self._port))
while not self._do_stop.is_set():
try:
msg = self._message.get_nowait()
sock.send_json(msg)
except queue.Empty:
time.sleep(0.01)
def stop(self):
self._do_stop.set()
def send_message(self, msg):
self._messages.put(msg)
def main():
data = zip(['2.2.2.2', '5.5.5.5'], [5001, 5002])
# create senders
senders = {device: Sender(port) for device, port in data}
# start senders
for device in senders:
senders[device].start()
# send messages
for device, port in zip(['2.2.2.2', '5.5.5.5'],[5001, 5002]):
msg = {device: 'Some random message'}
senders[device].send_message(msg)
# do more stuff here....
# ... e.g. send more messages
# ...
# once you are finished, stop the subprocesses
for device in senders:
senders[device].stop()
我希望这有助于解决您的问题。
答案 1 :(得分:0)
在main()
中执行原始发布商代码后,类实例化过程会创建(即在main()
- 进程范围内),通过.__init__()
构造函数方法,它自己的 Context()
-instance,因此属于(包括所有它的派生子对象(套接字等))到 main()
强> -process。
接下来,对 Process(...)
的调用启动另外几个进程,这些进程接收类实例(这些实例已经创建了ZeroMQ不可共享的玩具) main()
- 使用范围。
可能的脏快速黑客可能是推迟ZeroMQ Context()
实例化 - 是的,只需将其从.__init__()
移至某些 .aDeferredSETUP()
,这将在每个已调整的Process()
- 进程内的不同使用范围内执行,与main()
- 进程不同,并且您应该完成,作为零共享安全地服从了。
class SendData:
def __init__(self, msg, port):
self.msg = msg
self.port = port
self.NotSETUP = True
self.ctx = None
self.sock = None
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ L8R
# ctx = zmq.Context()
# self.sock = ctx.socket( zmq.PUB )
# self.sock.bind( 'tcp://127.0.0.1:' + str( self.port ) )
# time.sleep( 1 )
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ L8R
def sender( self ):
if self.NotSETUP:
self.aDeferredSETUP()
self.sock.send_json( self.msg )
def aDeferredSETUP( self ): # create I/O-threads in Process(), not main()
self.ctx = zmq.Context()
self.sock = self.ctx.socket( zmq.PUB )
self.sock.bind( 'tcp://127.0.0.1:' + str( self.port ) )
time.sleep( 1 )