forked from stephenmcd/two-queues
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zmq_pubsub.py
57 lines (46 loc) · 1.58 KB
/
zmq_pubsub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import time
import zmq
class ZMQPubSub(object):
def __init__(self, host="127.0.0.1"):
context = zmq.Context()
self.pub = context.socket(zmq.PUSH)
self.pub.connect("tcp://%s:%s" % (host, 5562))
self.sub = context.socket(zmq.SUB)
self.sub.connect("tcp://%s:%s" % (host, 5561))
self.channels = set()
def publish(self, channel, message):
self.pub.send_unicode("%s %s" % (channel, message))
def subscribe(self, channels):
for channel in channels:
self.channels.add(channel)
self.sub.setsockopt(zmq.SUBSCRIBE, channel)
def unsubscribe(self, channels):
for channel in channels:
self.channels.remove(channel)
self.sub.setsockopt(zmq.UNSUBSCRIBE, channel)
def pubsub(self):
return self
def listen(self):
while True:
channel, _, data = self.sub.recv().partition(" ")
yield {"type": "message", "channel": channel, "data": data}
def serve(quiet):
context = zmq.Context()
receiver = context.socket(zmq.PULL)
receiver.bind("tcp://*:%s" % 5562)
sender = context.socket(zmq.PUB)
sender.bind("tcp://*:%s" % 5561)
last = time.time()
messages = 0
try:
while True:
sender.send(receiver.recv())
if not quiet:
messages += 1
now = time.time()
if now - last > 1:
print "%s msg/sec" % messages
last = now
messages = 0
except (KeyboardInterrupt, SystemExit):
pass