How to use the aiohttp.WSMsgType function in aiohttp

To help you get started, we’ve selected a few aiohttp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github armills / jsonrpc-websocket / tests.py View on Github external
def test_error(self):
        self.receive_queue.put_nowait(aiohttp.WSMessage(aiohttp.WSMsgType.ERROR, 0, ''))
github home-assistant / home-assistant / tests / components / websocket_api / test_init.py View on Github external
def test_invalid_json(websocket_client):
    """Test sending invalid JSON."""
    yield from websocket_client.send_str("this is not JSON")

    msg = yield from websocket_client.receive()

    assert msg.type == WSMsgType.close
github mdellavo / rogue / rogue / server.py View on Github external
if response is None:
                break
            try:
                await ws.send_bytes(msgpack.packb(response))
            except Exception:
                log.error("writer closed")
                break
        if not ws.closed:
            await ws.close()
        log.info("writer stopped")

    writer = asyncio.create_task(_writer())
    updater = asyncio.create_task(_updater())

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.BINARY:
            obj = msgpack.unpackb(msg.data, raw=False)
            _handle_message(request.app["world"], player, obj)
        elif msg.type == aiohttp.WSMsgType.ERROR:
            log.error('ws connection closed with exception %s', ws.exception())
            break
        if not player.is_alive:
            break

    player.send_message()
    updater_queue.put_nowait(None)

    log.info("reader stopped")

    if not ws.closed:
        await ws.close()
github Remmeauth / remme-core / remme / ws / basic.py View on Github external
async def subscriptions(self, request):
        if not self._accepting:
            return web.Response(status=503)

        web_sock = web.WebSocketResponse()
        await web_sock.prepare(request)

        async for msg in web_sock:
            if msg.type == aiohttp.WSMsgType.TEXT:
                try:
                    await self._handle_message(web_sock, msg.data)
                except SocketException as e:
                    await self._ws_send_error(e.web_sock, e.error_code, e.info)

            elif msg.type == aiohttp.WSMsgType.ERROR:
                LOGGER.warning(
                    'Web socket connection closed with exception %s',
                    web_sock.exception())
                await web_sock.close()

        await self._handle_unsubscribe(web_sock)

        return web_sock
github GlasgowEmbedded / glasgow / software / glasgow / applet / audio / yamaha_opx / __init__.py View on Github external
async def serve_vgm(self, request):
        sock = aiohttp.web.WebSocketResponse()
        await sock.prepare(request)

        headers = await sock.receive_json()
        vgm_msg = await sock.receive()

        if vgm_msg.type == aiohttp.WSMsgType.BINARY:
            vgm_data = vgm_msg.data
        elif vgm_msg.type == aiohttp.WSMsgType.TEXT:
            self._logger.info("web: URL %s submitted by %s",
                              vgm_msg.data, request.remote)

            async with aiohttp.ClientSession() as client_sess:
                async with client_sess.get(vgm_msg.data) as client_resp:
                    if client_resp.status != 200:
                        await sock.close(code=2000 + client_resp.status,
                                         message=client_resp.reason)
                        return sock

                    if ("Content-Length" not in client_resp.headers or
                            int(client_resp.headers["Content-Length"]) > (1<<20)):
                        await sock.close(code=2999, message=
                            "File too large ({} bytes) to be fetched"
github HackerDom / ructfe-2016 / checkers / thebin / networking.py View on Github external
async def start_internal(self):
		async with self.connection as ws:
			async for msg in ws:
				if msg.type == aiohttp.WSMsgType.TEXT:
					try:
						data = msg.json(loads = lambda s : checker.parse_json(s, ['url', 'owner']))
					except Exception as ex:
						checher.mumble(error='can\'t parse service responce', exception=ex)
					await self.queue.put((data['url'], data['owner']))
				elif msg.type == aiohttp.WSMsgType.CLOSED:
					break
				else:
					checker.mumble(error='get message with unexpected type {}\nmessage: {}'.format(msg.type, msg.data))
	def want(self, url, owner):
github guilhermelawless / nano-dpow / server / dpow_server.py View on Github external
if type(data) != dict:
                            raise InvalidRequest("Bad request (not json)")
                        request_id = data.get('id', None)
                        response = await self.service_handler(data)
                    except InvalidRequest as e:
                        response = dict(error=e.reason)
                    except RequestTimeout:
                        response = dict(error="Timeout reached without work", timeout=True)
                    except Exception as e:
                        response = dict(error=f"Unknown error, please report the following timestamp to the maintainers: {datetime.datetime.now()}")
                        logger.critical(traceback.format_exc())
                    finally:
                        if request_id:
                            response['id'] = request_id
                        await ws.send_json(response)
                elif msg.type == WSMsgType.ERROR:
                    # logger.error(f"ws connection closed with exception {ws.exception()}")
                    pass
        except Exception:
            pass

        # logger.info('websocket connection closed')
        return ws
github aio-libs / aiohttp / examples / client_ws.py View on Github external
def dispatch():
        while True:
            msg = yield from ws.receive()

            if msg.type == aiohttp.WSMsgType.TEXT:
                print('Text: ', msg.data.strip())
            elif msg.type == aiohttp.WSMsgType.BINARY:
                print('Binary: ', msg.data)
            elif msg.type == aiohttp.WSMsgType.PING:
                ws.pong()
            elif msg.type == aiohttp.WSMsgType.PONG:
                print('Pong received')
            else:
                if msg.type == aiohttp.WSMsgType.CLOSE:
                    yield from ws.close()
                elif msg.type == aiohttp.WSMsgType.ERROR:
                    print('Error during receive %s' % ws.exception())
                elif msg.type == aiohttp.WSMsgType.CLOSED:
                    pass

                break
github pyslackers / slack-sansio / slack / io / aiohttp.py View on Github external
async def _rtm(self, url: str) -> AsyncIterator[str]:

        async with self._session.ws_connect(url) as ws:
            async for data in ws:
                if data.type == aiohttp.WSMsgType.TEXT:
                    yield data.data
                elif data.type == aiohttp.WSMsgType.CLOSED:
                    break
                elif data.type == aiohttp.WSMsgType.ERROR:
                    break
github rokups / Launchpad / src / common / transport / ws.py View on Github external
async def _native_recv(self):
        while True:
            try:
                msg = await self._socket.receive()
            except TypeError:
                return None
            except TimeoutError:
                return None

            if msg.type == aiohttp.WSMsgType.TEXT:
                msg = json.loads(msg.data)
            elif msg.type == aiohttp.WSMsgType.BINARY:
                msg = cbor2.loads(msg.data, tag_hook=encoder.cbor2_decoder)
            elif msg.type == aiohttp.WSMsgType.CLOSING:
                pass
            elif msg.type == aiohttp.WSMsgType.CLOSED or msg.type == aiohttp.WSMsgType.CLOSE:
                raise EOFError()
            elif msg.type == aiohttp.WSMsgType.ERROR:
                raise ConnectionError() from self._socket.exception()
            else:
                raise ValueError('Unhandled result type')

            logging.debug('>> ' + str(msg))
            # Greenlet is spawned here in order to not block main loop. Message handler may send messages and
            # wait for response. In order to get a response this loop must be spinning.
            fut = asyncio.get_event_loop().create_task(self.on_recv(msg))
            fut.add_done_callback(lambda f: f.exception())  # make sure exception is retrieved