Beispiel #1
0
 def __init__(self, server, username, password):
     self.data = ClientData(server, username, password)
     self._holder = AsyncHolder()
     self.api = ClientAPI(self.data, self.ws, self._holder)
     self._queue = Queue()
     self._stop = False
     self._ws = None
Beispiel #2
0
class Client:
    def __init__(self, server, username, password):
        self.data = ClientData(server, username, password)
        self._holder = AsyncHolder()
        self.api = ClientAPI(self.data, self.ws, self._holder)
        self._queue = Queue()
        self._stop = False
        self._ws = None

    def ws(self):
        return self._ws

    @property
    def stop(self):
        return self._stop

    @stop.setter
    def stop(self, value):
        if value:
            self._stop = True
            self._queue.put_nowait(None)

    async def network_loop(self, loop):
        async with sock.session(loop) as session:
            async with sock.connect(session, self.data.server) as ws:
                self._ws = ws
                async for msg in sock.ws_loop(ws):
                    self._queue.put_nowait(msg)

    async def handler_loop(self):
        while not self.stop:
            msg = await self._queue.get()
            if not msg:
                continue
            msgtype = parse.base.msg_type(msg)
            if msgtype == RawMessageType.NONE:
                self.do_connect()
            elif msgtype == RawMessageType.PING:
                self.api.send_pong()
            elif msgtype == RawMessageType.CONNECTED:
                self.session = parse.connected.parse(msg)['session']
                asyncio.ensure_future(self.do_login())
            elif msgtype == RawMessageType.RESULT:
                self._holder.recv_result(msg)
            elif msgtype == RawMessageType.READY:
                self._holder.recv_ready(msg)
            else:
                asyncio.ensure_future(self.parse(msg, msgtype))

    async def parse(self, msg, msgtype):
        raise NotImplementedError

    async def do_login(self):
        await self.api.login()

    def do_connect(self):
        self.api.connect()