2017-11-27 17:20:54 +00:00
|
|
|
import json
|
2017-11-27 17:20:09 +00:00
|
|
|
import zmq
|
|
|
|
from zmq.eventloop import ioloop
|
|
|
|
from zmq.eventloop.zmqstream import ZMQStream
|
|
|
|
|
|
|
|
from config import PUBLISHER_PORT, RECEIVER_PORT
|
|
|
|
|
|
|
|
ioloop.install()
|
|
|
|
|
|
|
|
|
2017-12-02 14:19:05 +00:00
|
|
|
class EventHandlerBase:
|
2017-12-03 01:13:19 +00:00
|
|
|
def __init__(self, anchor, zmq_context=None):
|
2017-11-27 17:20:09 +00:00
|
|
|
self.anchor = anchor
|
|
|
|
self.zmq_context = zmq_context or zmq.Context.instance()
|
|
|
|
self.zmq_sub_socket = self.zmq_context.socket(zmq.SUB)
|
2017-11-27 17:34:26 +00:00
|
|
|
self.subscriptions = {self.anchor}
|
|
|
|
self.zmq_sub_socket.setsockopt_string(zmq.SUBSCRIBE, self.anchor)
|
2017-11-27 17:20:09 +00:00
|
|
|
self.zmq_sub_socket.connect('tcp://localhost:{}'.format(PUBLISHER_PORT))
|
|
|
|
self.zmq_sub_stream = ZMQStream(self.zmq_sub_socket)
|
|
|
|
self.zmq_push_socket = self.zmq_context.socket(zmq.PUSH)
|
|
|
|
self.zmq_push_socket.connect('tcp://localhost:{}'.format(RECEIVER_PORT))
|
2018-01-17 13:26:16 +00:00
|
|
|
self.zmq_sub_stream.on_recv(self.event_handler_callback)
|
|
|
|
|
|
|
|
def event_handler_callback(self, msg_parts):
|
|
|
|
anchor, message = msg_parts
|
|
|
|
data_json = json.loads(message)
|
|
|
|
response = self.handle_event(anchor, data_json)
|
|
|
|
if response is None: return
|
|
|
|
encoded_response = json.dumps(response).encode('utf-8')
|
|
|
|
self.zmq_push_socket.send_multipart([anchor, encoded_response])
|
|
|
|
|
|
|
|
def handle_event(self, anchor, data_json):
|
|
|
|
raise NotImplementedError
|
2017-11-27 17:20:09 +00:00
|
|
|
|
2017-11-27 17:20:54 +00:00
|
|
|
def message_other(self, anchor, data):
|
|
|
|
encoded_anchor = anchor.encode('utf-8')
|
|
|
|
message = {
|
|
|
|
'anchor': anchor,
|
|
|
|
'data': data
|
|
|
|
}
|
|
|
|
encoded_message = json.dumps(message).encode('utf-8')
|
|
|
|
self.zmq_push_socket.send_multipart([encoded_anchor, encoded_message])
|
|
|
|
|
2017-11-27 17:34:26 +00:00
|
|
|
def subscribe(self, anchor):
|
|
|
|
if anchor not in self.subscriptions:
|
|
|
|
self.subscriptions.add(anchor)
|
2017-12-03 01:13:19 +00:00
|
|
|
self.zmq_sub_socket.setsockopt_string(
|
|
|
|
zmq.SUBSCRIBE, anchor
|
|
|
|
)
|
2017-11-27 17:34:26 +00:00
|
|
|
|
|
|
|
def unsubscribe(self, anchor):
|
|
|
|
try:
|
|
|
|
self.subscriptions.remove(anchor)
|
|
|
|
self.zmq_sub_socket.setsockopt_string(zmq.UNSUBSCRIBE, anchor)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def unsubscribe_all(self):
|
|
|
|
for sub in self.subscriptions:
|
|
|
|
self.zmq_sub_socket.setsockopt_string(zmq.UNSUBSCRIBE, sub)
|
|
|
|
self.subscriptions.clear()
|