[zeromq-dev] How to make recv() non blocking

Dan Fairs dan.fairs at gmail.com
Tue Apr 3 11:44:17 CEST 2012


> I got your way of using NOBLOCK, but can you brief me more about how i can use zmq.poll here using the POLLIN and POLLOUT events.


Here's an (edited) highlight from our codebase:

        control_socket = self.context.socket(zmq.SUB)
        control_socket.setsockopt(zmq.SUBSCRIBE, '')
        control_socket.connect(self.control_addr)

        timer_socket = self.context.socket(zmq.SUB)
        timer_socket.setsockopt(zmq.SUBSCRIBE, '')
        timer_socket.connect('inproc://timer')

        poller = zmq.Poller()
        poller.register(control_socket, zmq.POLLIN)
        poller.register(timer_socket, zmq.POLLIN)

        while not self.stop:
            socks = dict(poller.poll(500))
            if socks.get(control_socket) == zmq.POLLIN:
                message = control_socket.recv()
                self.handle_control(message)
            if socks.get(timer_socket) == zmq.POLLIN:
                message = timer_socket.recv()
                self.handle_timer(message)
            self.logger.debug(u'Heartbeat')

        control_socket.close()
        timer_socket.close()

Hope that helps. It's very similar to the example in the zguide, to be honest, make sure you have a good read of that.

Note that this is only really appropriate if you want to check multiple sockets. If you've just got the one socket, something like this might be more appropriate:

        while not self.stop:
            try:
                raw_message = self.pull_socket.recv(zmq.NOBLOCK)
            except zmq.ZMQError as e:
                if e.errno != zmq.EAGAIN:
                    raise
                time.sleep(.5)
	        self.logger.debug(u'Heartbeat')
            else:
                self.sync_handle(raw_message)


Cheers,
Dan
--
Dan Fairs | dan.fairs at gmail.com | www.fezconsulting.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.zeromq.org/pipermail/zeromq-dev/attachments/20120403/fe061729/attachment.htm>


More information about the zeromq-dev mailing list