Created
July 30, 2012 23:09
-
-
Save spenthil/3211707 to your computer and use it in GitHub Desktop.
pyzmq: ioloop in separate thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zmq, zmq.eventloop.zmqstream,zmq.eventloop.ioloop | |
import threading | |
import logging | |
logging.basicConfig(level=logging.DEBUG) | |
logger = logging.getLogger() | |
zmq.eventloop.ioloop.install() | |
# run ioloop in separate thread | |
def threaded_loop(): | |
while True: | |
logger.debug("starting IOLoop") | |
zmq.eventloop.ioloop.IOLoop.instance().start() | |
t = threading.Thread(target=threaded_loop) | |
t.daemon = True | |
t.start() | |
context = zmq.Context() | |
# like echo - but better | |
def exclaim(stream, msg): | |
stream.send("{}!".format(msg[0].upper())) | |
address = "tcp://127.0.0.1:20120" | |
rep = context.socket(zmq.REP) | |
rep.bind(address) | |
rep_stream = zmq.eventloop.zmqstream.ZMQStream(rep) | |
rep_stream.on_recv_stream(exclaim) | |
# the thread ioloop is wrapped in a `while True` so it | |
# will immediately start up again - we stop it so it picks up (?) the | |
# newly added `REP` stream | |
zmq.eventloop.ioloop.IOLoop.instance().stop() | |
req = context.socket(zmq.REQ) | |
logger.debug("connecting") | |
req.connect(address) | |
logger.debug("sending") | |
req.send("steveholt") | |
logger.debug("receiving") | |
assert(req.recv() == "STEVEHOLT!") | |
logger.debug("done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output from the above: