mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-06 00:01:20 +00:00
50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
import json
|
|
import zmq
|
|
from zmq.eventloop import ioloop
|
|
from zmq.eventloop.zmqstream import ZMQStream
|
|
|
|
from config import PUBLISHER_PORT, RECEIVER_PORT
|
|
|
|
ioloop.install()
|
|
|
|
|
|
class EventHandlerBase:
|
|
def __init__(self, anchor, zmq_context=None):
|
|
self.anchor = anchor
|
|
self.zmq_context = zmq_context or zmq.Context.instance()
|
|
self.zmq_sub_socket = self.zmq_context.socket(zmq.SUB)
|
|
self.subscriptions = {self.anchor}
|
|
self.zmq_sub_socket.setsockopt_string(zmq.SUBSCRIBE, self.anchor)
|
|
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))
|
|
|
|
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])
|
|
|
|
def subscribe(self, anchor):
|
|
if anchor not in self.subscriptions:
|
|
self.subscriptions.add(anchor)
|
|
self.zmq_sub_socket.setsockopt_string(
|
|
zmq.SUBSCRIBE, anchor
|
|
)
|
|
|
|
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()
|