multi-user/message.py

76 lines
2.1 KiB
Python
Raw Normal View History

2019-04-30 17:18:41 +02:00
import logging
2019-04-10 17:01:21 +02:00
try:
from .libs import umsgpack
2019-05-09 14:20:42 +02:00
2019-04-10 17:01:21 +02:00
except:
# Server import
from libs import umsgpack
2019-05-09 14:20:42 +02:00
import zmq
2019-04-10 17:01:21 +02:00
2019-04-30 17:18:41 +02:00
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
2019-04-10 17:01:21 +02:00
class RCFMessage(object):
"""
Message is formatted on wire as 2 frames:
frame 0: key (0MQ string) // property path
frame 1: id (0MQ string) // property path
frame 3: body (blob) // Could be any data
"""
key = None # key (string)
id = None # User (string)
body = None # data blob
2019-04-24 18:21:07 +02:00
def __init__(self, key=None, id=None, body=None):
2019-04-10 17:01:21 +02:00
self.key = key
self.body = body
self.id = id
2019-04-30 17:18:41 +02:00
def store(self, dikt):
2019-04-10 17:01:21 +02:00
"""Store me in a dict if I have anything to store"""
# this currently erasing old value
2019-04-30 17:18:41 +02:00
if self.key is not None:
if self.body == 'None':
2019-04-30 17:18:41 +02:00
logger.info("erasing key {}".format(self.key))
del dikt[self.key]
else:
dikt[self.key] = self
2019-04-30 17:18:41 +02:00
2019-04-10 17:01:21 +02:00
def send(self, socket):
"""Send key-value message to socket; any empty frames are sent as such."""
key = ''.encode() if self.key is None else self.key.encode()
2019-04-30 17:18:41 +02:00
body = umsgpack.packb('None') if self.body is None else umsgpack.packb(self.body)
2019-04-10 17:01:21 +02:00
id = ''.encode() if self.id is None else self.id
try:
socket.send_multipart([key, id, body])
2019-04-10 17:01:21 +02:00
except:
2019-04-30 17:18:41 +02:00
print("Fail to send {} {} {}".format(key, id, body))
2019-04-10 17:01:21 +02:00
@classmethod
def recv(cls, socket):
"""Reads key-value message from socket, returns new kvmsg instance."""
2019-04-29 16:39:11 +02:00
key, id, body = socket.recv_multipart(zmq.NOBLOCK)
2019-04-10 17:01:21 +02:00
key = key.decode() if key else None
id = id if id else None
body = umsgpack.unpackb(body) if body else None
return cls(key=key, id=id, body=body)
2019-04-10 17:01:21 +02:00
def dump(self):
if self.body is None:
size = 0
data = 'NULL'
else:
size = len(self.body)
data = repr(self.body)
2019-04-24 18:21:07 +02:00
print("[key:{key}][size:{size}] {data}".format(
2019-04-10 17:01:21 +02:00
key=self.key,
size=size,
data=data,
))