Skip to content

Instantly share code, notes, and snippets.

@anopheles
Created September 12, 2012 13:34
Show Gist options
  • Save anopheles/3706633 to your computer and use it in GitHub Desktop.
Save anopheles/3706633 to your computer and use it in GitHub Desktop.
Router Dealer example with bidirectional communication
# encoding: utf-8
import zmq
from collections import defaultdict
context = zmq.Context()
client = context.socket(zmq.ROUTER)
client.bind("tcp://*:5556")
poll = zmq.Poller()
poll.register(client, zmq.POLLIN)
counter = defaultdict(int)
while True:
# handle input
sockets = dict(poll.poll(1000))
if sockets:
identity = client.recv()
msg = client.recv()
counter[identity] += 1
# start recording
for identity in counter.keys():
client.send(identity, zmq.SNDMORE)
client.send("START")
print counter
# encoding: utf-8
import random
import zmq
import time
context = zmq.Context()
worker = context.socket(zmq.DEALER)
worker.setsockopt(zmq.IDENTITY, str(random.randint(0, 8000)))
worker.connect("tcp://localhost:5556")
start = False
worker.send("Hello")
while True:
if start:
worker.send("recording data: %s" % random.randint(0,100))
time.sleep(0.5)
request = worker.recv()
if request == "START":
start = True
if request == "STOP":
start = False
if request == "END":
print "A is finishing"
break
@ashwynh21
Copy link

A simple and elegant example, thank you...it cleared a lot of misunderstandings I had from working with ZMQ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment