forked from eastein/chillmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzmqsub.py
78 lines (65 loc) · 1.65 KB
/
zmqsub.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import zmq
import json
class NoMessagesException(Exception) :
pass
class JSONZMQSub(object) :
def __init__(self, url) :
self.c = zmq.Context(1)
self.s = self.c.socket(zmq.SUB)
self.s.connect(url)
self.s.setsockopt (zmq.SUBSCRIBE, "")
self._last = None
def last_msg(self) :
r = [self.s]
msg = None
while r :
r, w, x = zmq.core.poll.select([self.s], [], [], 0.0)
if r :
msg = self.s.recv()
r, w, x = zmq.core.poll.select([self.s], [], [], 0.05)
if r :
msg = self.s.recv()
if msg is not None :
self._last = json.loads(msg)
return self._last
def recv(self) :
msg = None
r, w, x = zmq.core.poll.select([self.s], [], [], 0.0)
if r :
msg = self.s.recv()
self._last = json.loads(msg)
return self._last
else :
raise NoMessagesException
class JSONZMQBindSub(object) :
def __init__(self, url) :
self.c = zmq.Context(1)
self.s = self.c.socket(zmq.SUB)
self.s.bind(url)
self.s.setsockopt (zmq.SUBSCRIBE, "")
def recv(self) :
msg = None
r, w, x = zmq.core.poll.select([self.s], [], [], 0.0)
if r :
msg = self.s.recv()
self._last = json.loads(msg)
return self._last
else :
raise NoMessagesException
class JSONZMQBindPub(object) :
def __init__(self, url) :
self.c = zmq.Context(1)
self.s = self.c.socket(zmq.PUB)
self.s.bind(url)
def send(self, msg) :
self.s.send(json.dumps(msg))
class JSONZMQConnectPub(object) :
def __init__(self, url) :
self.c = zmq.Context(1)
self.s = self.c.socket(zmq.PUB)
self.s.connect(url)
# unreliable send, but won't block forever.
def send(self, msg) :
r, w, x = zmq.core.poll.select([], [self.s], [], 10.0)
if w :
self.s.send(json.dumps(msg))