-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcenpubsub.py
102 lines (64 loc) · 1.61 KB
/
cenpubsub.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/python
import json
# Centralized pub/sub
# Some constants
BROKER_PORT = 8888
SUB_PORT = 9999
SUB_MSG_KEY = 'SUB'
PUB_MSG_KEY = 'PUB'
EVENT_MSG_KEY = 'EVENT'
PAYLOAD_KEY = 'PAYLOAD'
NO_SUB_ID = -1 # Special id value for new subscription requests
ID_KEY = 'ID'
TOPICS_KEY = 'TOPICS'
MAX_CONN = 5
RECV_BUFSIZ= 4096
# Message types
# Every message is just JSON
class SubscribeMsg():
'''
A subscription request message.
This serves as both a 'join' request and/or a subscribe one.
'''
def __init__(self, topics):
assert len(topics) > 0
self.topics = topics
def to_json(self):
d = {
SUB_MSG_KEY: {
TOPICS_KEY: self.topics
}
}
return json.dumps(d, indent=4)
class PublishMsg():
'''
A publish message
'''
def __init__(self, topic, payload):
self.topics = [topic]
self.payload = payload
def to_json(self):
d = {
PUB_MSG_KEY: {
TOPICS_KEY: self.topics,
PAYLOAD_KEY: self.payload
}
}
return json.dumps(d, indent=4)
class EventMsg():
'''
An event (i.e. forwarded published msg) message
'''
def __init__(self, topic, payload):
self.topics = [topic]
self.payload = payload
def to_json(self):
d = {
EVENT_MSG_KEY: {
TOPICS_KEY: self.topics,
PAYLOAD_KEY: self.payload
}
}
return json.dumps(d, indent=4)
class BadPubSubMsgError(Exception):
pass