为什么这个zmq代码不起作用?

时间:2015-04-14 20:55:08

标签: python zeromq python-multiprocessing

此测试不起作用。

class PrintHandler(MessageHandler):
    def handle_message(self, message):
        print(message)

class FileHandler(MessageHandler):
    def handle_message(self, message):
        with open('nana', 'w') as f:
            f.write(message)


class SubscribeProcess(Process):


    def __init__(self, handler):
        super(SubscribeProcess, self).__init__(group=None, target=None, name=None, args=(), kwargs={})
        self.handler = handler


    def run(self):

        self.address = TcpAddress(host='127.0.0.1', port=5555)
        subscriber = ZmqSubscriber(ZmqBlockingConnection(address=self.address, bind=False))
        subscriber.set_message_handler(self.handler)
        print('............')


class TestZmqSubscriber(TestCase):
    def test_set_message_handler(self):
        address = TcpAddress(host='127.0.0.1', port=5555)
        pub_connection = ZmqBlockingConnection(address, bind=True)
        publisher = ZmqPublisher(pub_connection)
        p = SubscribeProcess(handler=PrintHandler())
        p.start()
        while True:
            publisher.publish('Message number {}'.format(2))

我现在认为这不是单元测试。但我希望先在控制台中看到收到的消息。然后我会写适当的测试。

虽然这两个脚本完美无缺。

connection = ZmqBlockingConnection(TcpAddress(host='127.0.0.1', port=5555), bind=False)
sub = ZmqSubscriber(connection)
sub.set_message_handler(PrintHandler())

address = TcpAddress(host='127.0.0.1', port=5555)
pub_connection = ZmqBlockingConnection(address, bind=True)
publisher = ZmqPublisher(pub_connection)
while True:
    publisher.publish('Message number {}'.format(2))

subscriber.set_message_handler(handler)内部实际上就是这个

def start_receiving_messages(self, message_handler):
    while True:
        message_handler.handle_message(self.socket.recv())

在调试器中,我看到代码在socket.recv()

中无限挂起

也许我正在使用多处理错误?

EDIT1

class ZmqBlockingConnection(Connection):

def start_receiving_messages(self, message_handler):
    while True:
        message_handler.handle_message(self.socket.recv())

def send_message(self, message):
    self.socket.send(message)

def __init__(self, address, bind, hwm=1000):
    self.hwm = hwm
    self.bind = bind
    self.address = address
    self.socket = None

def set_hwm(self, hwm):
    self.socket.set_hwm(hwm)

def configure(self, socket_type):
    self.socket = zmq.Context().socket(socket_type)
    if self.bind:
        self.socket.bind(str(self.address))
    else:
        self.socket.connect(str(self.address))
    self.set_hwm(self.hwm)

1 个答案:

答案 0 :(得分:0)

好的,问题出在

def configure(self, socket_type):
self.socket = zmq.Context().instance().socket(socket_type)
if self.bind:
    self.socket.bind(str(self.address))
else:
    self.socket.connect(str(self.address))
self.set_hwm(self.hwm)

因此我开始创建上下文实例而不是使用单例,现在它正在工作。