class MessageQueue(object): def __init__(self, my_ident): self.me = my_ident self.link = Link() self.packeter = Packeter(self.link) self.messaging = Messaging(my_ident, '', self.packeter) self.link.on_loop_pass.add(self.on_loop) self.messaging.on_message_recv.add(self.on_recv) self.messaging.on_disconnect.add(self.on_disconnect) self.messaging.on_connect.add(self.on_connect) def loop(self): self.link.loop() def listen(self, port=4000): self.link.add_listener(('', port)) def connect(self, host, port): self.link.add_connector((host, port)) def cleanup(self): self.link.cleanup() def on_receive_json(self, ident, obj, mid64): pass def send_json(self, ident, obj, ttl=600): _json = json.dumps(obj) message = Message(bytes(_json), ttl) log.debug('send_json -> [%s]: %s %s', ident, obj, repr(get_mid64(message))) self.messaging.send_message(ident, message) return message def on_connect(self, conn, ident): pass def on_recv(self, conn, ident, message): log.debug('on_recv <- [%s]: %s', ident, message) mid64 = get_mid64(message) try: obj = json.loads(message.data) self.on_receive_json(ident, obj, mid64) except ValueError: self.send_json(ident, {'error': 'invalid_json', 'message': str(message.data), 'src_mid64': mid64}) log.error('invalid_json: %s', message.data) def on_disconnect(self, conn, ident): pass def on_loop(self): pass
def __init__(self, my_ident): self.me = my_ident self.link = Link() self.packeter = Packeter(self.link) self.messaging = Messaging(my_ident, '', self.packeter) self.link.on_loop_pass.add(self.on_loop) self.messaging.on_message_recv.add(self.on_recv) self.messaging.on_disconnect.add(self.on_disconnect) self.messaging.on_connect.add(self.on_connect)