Skip to content

Instantly share code, notes, and snippets.

@sytelus
Forked from minrk/gist:3213317
Created December 12, 2018 09:34
Show Gist options
  • Save sytelus/f4eae841a39af343162a7d0518347598 to your computer and use it in GitHub Desktop.
Save sytelus/f4eae841a39af343162a7d0518347598 to your computer and use it in GitHub Desktop.
pyzmq: ioloop in separate thread
import zmq
from zmq.eventloop import zmqstream, ioloop
import threading
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
# run ioloop in separate thread
def threaded_loop():
logger.debug("starting IOLoop")
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"
def make_rep_stream():
rep = context.socket(zmq.REP)
rep.bind(address)
rep_stream = zmqstream.ZMQStream(rep)
rep_stream.on_recv_stream(exclaim)
# any calls to IOLoop API methods must be made via add_callback
# while the IOLoop is running in another thread:
ioloop.IOLoop.instance().add_callback(make_rep_stream)
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