multi-user/net_components.py

216 lines
6.4 KiB
Python
Raw Normal View History

import zmq
import asyncio
import logging
2019-02-08 18:34:10 +01:00
from .libs import umsgpack
2019-02-11 15:48:07 +01:00
from .libs import kvsimple
import time
import random
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
2019-02-11 16:25:08 +01:00
2019-02-07 18:07:25 +01:00
class Session():
def __init__(self, host='127.0.0.1', port=5555, is_hosting=False):
self.host = host
self.port = port
2019-02-08 18:34:10 +01:00
self.is_running = False
# init zmq context
self.context = zmq.Context()
2019-02-08 18:34:10 +01:00
self.socket = None
2019-02-11 16:25:08 +01:00
self.msg = []
2019-02-11 16:25:08 +01:00
# self.listen.add_done_callback(self.close_success())
# TODO: Add a kill signal to destroy clients session
# TODO: Add a join method
# TODO: Add a create session method
2019-02-08 18:34:10 +01:00
def join(self):
logger.info("joinning {}:{}".format(self.host, self.port))
try:
2019-02-11 15:48:07 +01:00
self.socket = self.context.socket(zmq.DEALER)
2019-02-08 18:34:10 +01:00
self.socket.connect("tcp://localhost:5555")
self.listen = asyncio.ensure_future(self.listen())
2019-02-11 16:25:08 +01:00
2019-02-11 15:48:07 +01:00
self.send("XXX connected")
2019-02-08 18:34:10 +01:00
return True
except zmq.ZMQError:
logger.error("Error while joining {}:{}".format(
self.host, self.port))
return False
# TODO: Find better names
def create(self):
logger.info("Creating session")
try:
2019-02-11 15:48:07 +01:00
self.socket = self.context.socket(zmq.ROUTER)
2019-02-08 18:34:10 +01:00
self.socket.bind("tcp://*:5555")
self.listen = asyncio.ensure_future(self.listen())
return True
except zmq.ZMQError:
2019-02-11 16:25:08 +01:00
logger.error("Error while creating session: ", zmq.ZMQError)
2019-02-08 18:34:10 +01:00
return False
async def listen(self):
logger.info("Listening on {}:{}".format(self.host, self.port))
2019-02-08 18:34:10 +01:00
self.is_running = True
while True:
# Ungly blender workaround to prevent blocking...
await asyncio.sleep(0.016)
try:
2019-02-11 15:48:07 +01:00
buffer = self.socket.recv(zmq.NOBLOCK)
message = umsgpack.unpackb(buffer)
if message is not 0:
self.socket.send(umsgpack.packb(0))
self.msg.append()
except zmq.ZMQError:
pass
def send(self, msg):
logger.info("Sending {} to {}:{} ".format(msg, self.host, self.port))
2019-02-11 15:48:07 +01:00
self.msg.append(msg)
2019-02-08 18:34:10 +01:00
bin = umsgpack.packb(msg)
2019-02-11 15:48:07 +01:00
self.socket.send(bin)
2019-02-08 18:34:10 +01:00
async def close_success(self):
self.is_running = False
def close(self):
logger.info("Closing session")
2019-02-08 18:34:10 +01:00
self.socket.close()
self.listen.cancel()
2019-02-08 18:34:10 +01:00
del self.listen
self.is_running = False
2019-02-11 15:48:07 +01:00
2019-02-11 16:25:08 +01:00
2019-02-11 15:48:07 +01:00
class Client():
def __init__(self, context=zmq.Context(), id="default", recv_callback=None):
2019-02-11 16:25:08 +01:00
self.context = context
self.pull_sock = None
self.push_sock = None
self.poller = None
2019-02-11 16:25:08 +01:00
self.id = id
self.recv_callback = recv_callback
2019-02-11 16:25:08 +01:00
self.bind_ports()
# Main client loop registration
self.task = asyncio.ensure_future(self.main())
2019-02-11 17:31:03 +01:00
self.store = []
2019-02-11 16:25:08 +01:00
logger.info("{} client initialized".format(id))
def bind_ports(self):
# pull socket: get update FROM server
self.pull_sock = self.context.socket(zmq.SUB)
self.pull_sock.linger = 0
self.pull_sock.connect("tcp://localhost:5555")
self.pull_sock.setsockopt_string(zmq.SUBSCRIBE, '')
# push socket: push update TO server
self.push_sock = self.context.socket(zmq.DEALER)
self.push_sock.setsockopt(zmq.IDENTITY, self.id.encode())
self.push_sock.linger = 0
self.push_sock.connect("tcp://localhost:5556")
# Sockets aggregator, not really used for now
self.poller = zmq.Poller()
self.poller.register(self.pull_sock, zmq.POLLIN)
async def main(self):
logger.info("{} client launched".format(id))
2019-02-11 18:10:56 +01:00
2019-02-11 15:48:07 +01:00
# Prepare our context and publisher socket
while True:
2019-02-11 16:25:08 +01:00
# TODO: find a better way
2019-02-11 15:48:07 +01:00
await asyncio.sleep(0.016)
try:
2019-02-11 16:25:08 +01:00
socks = dict(self.poller.poll(1))
except KeyboardInterrupt:
break
2019-02-11 15:48:07 +01:00
2019-02-11 16:25:08 +01:00
if self.pull_sock in socks:
message = self.pull_sock.recv_multipart(zmq.NOBLOCK)
logger.info("{}:{}".format(message[0].decode(
'ascii'), umsgpack.unpackb(message[1])))
2019-02-11 17:31:03 +01:00
# Store message
self.store.append(
[message[0].decode('ascii'), umsgpack.unpackb(message[1])])
if self.recv_callback:
self.recv_callback()
2019-02-11 16:25:08 +01:00
def send_msg(self, msg):
2019-02-11 17:02:25 +01:00
self.push_sock.send(umsgpack.packb(msg))
2019-02-11 15:48:07 +01:00
def stop(self):
logger.info("Stopping client")
2019-02-11 17:49:28 +01:00
self.poller.unregister(self.pull_sock)
2019-02-11 16:25:08 +01:00
self.push_sock.close()
self.pull_sock.close()
2019-02-11 17:49:28 +01:00
self.task.cancel()
2019-02-11 15:48:07 +01:00
class Server():
2019-02-11 16:25:08 +01:00
def __init__(self, context=zmq.Context(), id="admin"):
self.context = context
self.pub_sock = None
self.pull_sock = None
self.poller = None
self.id = id
self.bind_ports()
# Main client loop registration
self.task = asyncio.ensure_future(self.main())
logger.info("{} client initialized".format(id))
def bind_ports(self):
# Update all clients
self.pub_sock = self.context.socket(zmq.PUB)
self.pub_sock.bind("tcp://*:5555")
2019-02-11 15:48:07 +01:00
time.sleep(0.2)
2019-02-11 16:25:08 +01:00
# Update receiver
self.pull_sock = self.context.socket(zmq.ROUTER)
self.pull_sock.bind("tcp://*:5556")
2019-02-11 15:48:07 +01:00
2019-02-11 16:25:08 +01:00
# poller for socket aggregation
self.poller = zmq.Poller()
self.poller.register(self.pull_sock, zmq.POLLIN)
async def main(self):
logger.info("{} server launched".format(id))
# Prepare our context and publisher socket
2019-02-11 15:48:07 +01:00
while True:
2019-02-11 16:25:08 +01:00
# TODO: find a better way
2019-02-11 15:48:07 +01:00
await asyncio.sleep(0.016)
2019-02-11 16:25:08 +01:00
try:
socks = dict(self.poller.poll(1))
except KeyboardInterrupt:
break
if self.pull_sock in socks:
msg = self.pull_sock.recv_multipart(zmq.NOBLOCK)
2019-02-11 17:02:25 +01:00
#print("{}:{}".format(msg[0].decode('ascii'), umsgpack.packb(msg[1])))
2019-02-11 16:25:08 +01:00
# Update all clients
self.pub_sock.send_multipart(msg)
2019-02-11 15:48:07 +01:00
def stop(self):
logger.info("Stopping server")
2019-02-11 17:49:28 +01:00
self.poller.unregister(self.pull_sock)
2019-02-11 16:25:08 +01:00
self.pub_sock.close()
self.pull_sock.close()
2019-02-11 17:49:28 +01:00
self.task.cancel()