Skip to content

Instantly share code, notes, and snippets.

@fatih
Forked from minrk/rr.py
Created May 18, 2013 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatih/5602691 to your computer and use it in GitHub Desktop.
Save fatih/5602691 to your computer and use it in GitHub Desktop.
import os
import sys
import threading
import zmq
def worker(identity, wurl):
ctx = zmq.Context.instance()
s = ctx.socket(zmq.REP)
s.identity = identity
s.connect(wurl)
while True:
msg = s.recv_multipart()
print("%s received: %s" % (identity, msg))
s.send_multipart(msg + ['ack', 'from', identity])
def client(identity, curl):
ctx = zmq.Context.instance()
s = ctx.socket(zmq.REQ)
s.identity = identity
s.connect(curl)
return s
def _relay(ins, outs):
msg = ins.recv_multipart()
print("%s received %s" % (ins.identity, msg))
# the identity prefix is 3 parts for REQ-REP,
# but 2 parts for ROUTER-DEALER
if msg[1] == b'':
n = 3
else:
n = 2
# reverse the identities
msg[:n] = msg[:n][::-1]
outs.send_multipart(msg)
print("%s sent %s" % (outs.identity, msg))
def relay(curl, wurl):
ctx = zmq.Context.instance()
router1 = ctx.socket(zmq.ROUTER)
router1.identity = 'ROUTER 1'
router1.bind(curl)
router2 = ctx.socket(zmq.ROUTER)
router2.identity = 'ROUTER 2'
router2.bind(wurl)
poller = zmq.Poller()
poller.register(router1, zmq.POLLIN)
poller.register(router2, zmq.POLLIN)
while True:
events = dict(poller.poll())
if router1 in events:
_relay(router1, router2)
elif router2 in events:
_relay(router2, router1)
curl = "inproc://curl"
wurl = "inproc://wurl"
relayer = threading.Thread(target=relay, args=(curl, wurl))
relayer.start()
worker_identities = ['REP1', 'REP2']
workers = [ threading.Thread(target=worker, args=(ident, wurl)) for ident in worker_identities]
[ w.start() for w in workers ]
req1 = client('REQ1', curl)
req2 = client('REQ2', curl)
for wid in worker_identities:
msg = [wid, "hello from %s" % req1.identity]
print("REQ1 sent %s" % msg)
req1.send_multipart(msg)
msg = [wid, "hello from %s" % req2.identity]
print("REQ2 sent %s" % msg)
req2.send_multipart(msg)
print("REQ1 received: %s" % req1.recv_multipart())
print("REQ2 received: %s" % req2.recv_multipart())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment