Python aiohttp.web.WebSocketResponse() Examples

The following are 30 code examples of aiohttp.web.WebSocketResponse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: game_loop_handler.py    From snakepit-game with The Unlicense 7 votes vote down vote up
def wshandler(request):
    app = request.app
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    app["sockets"].append(ws)

    if app["game_is_running"] == False:
        asyncio.ensure_future(game_loop(app))
    while 1:
        msg = await ws.receive()
        if msg.tp == web.MsgType.text:
            print("Got message %s" % msg.data)
            ws.send_str("Pressed key code: {}".format(msg.data))
        elif msg.tp == web.MsgType.close or\
             msg.tp == web.MsgType.error:
            break

    app["sockets"].remove(ws)
    print("Closed connection")

    return ws 
Example #2
Source File: test_rproxy.py    From dffml with MIT License 6 votes vote down vote up
def handler(self, request):
        headers = request.headers
        if (
            headers.get("connection", "").lower() == "upgrade"
            and headers.get("upgrade", "").lower() == "websocket"
            and request.method == "GET"
        ):
            ws = web.WebSocketResponse()
            await ws.prepare(request)

            async for msg in ws:
                if msg.type == aiohttp.WSMsgType.TEXT:
                    await ws.send_str(msg.data)
                elif msg.type == aiohttp.WSMsgType.BINARY:
                    await ws.send_bytes(msg.data)
                elif msg.type == aiohttp.WSMsgType.PING:
                    await ws.ping()
                elif msg.type == aiohttp.WSMsgType.PONG:
                    await ws.pong()
                elif ws.closed:
                    await ws.close(code=ws.close_code, message=msg.extra)

            return ws
        else:
            return web.Response(text=request.path) 
Example #3
Source File: websocket_message_handler.py    From indy-agent with Apache License 2.0 6 votes vote down vote up
def ws_handler(self, request):

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

        if self.ws is not None:
            await self.ws.close()

        self.ws = ws

        _, unfinished = await asyncio.wait(
            [
                self._websocket_receive(ws),
                self._websocket_send(ws)
            ],
            return_when=asyncio.FIRST_COMPLETED
        )
        for task in unfinished:
            task.cancel()

        return ws 
Example #4
Source File: test_account_link.py    From hass-nabucasa with GNU General Public License v3.0 6 votes vote down vote up
def create_account_link_server(aiohttp_client, handle_server_msgs):
    """Create a websocket server."""

    async def websocket_handler(request):

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

        try:
            await handle_server_msgs(ws)
        finally:
            await ws.close()

        return ws

    app = web.Application()
    app.add_routes([web.get("/ws", websocket_handler)])
    client = await aiohttp_client(app)
    return await client.ws_connect("/ws") 
Example #5
Source File: tqwebhelper.py    From tqsdk-python with Apache License 2.0 6 votes vote down vote up
def connection_handler(self, request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)
        send_msg = self.get_send_msg(self._data)
        await ws.send_str(send_msg)
        conn_chan = TqChan(self._api, last_only=True)
        self._conn_diff_chans.add(conn_chan)
        try:
            async for msg in ws:
                pack = simplejson.loads(msg.data)
                if pack["aid"] == 'peek_message':
                    last_diff = await conn_chan.recv()
                    send_msg = self.get_send_msg(last_diff)
                    await ws.send_str(send_msg)
        except Exception as e:
            await conn_chan.close()
            self._conn_diff_chans.remove(conn_chan) 
Example #6
Source File: game_loop_basic.py    From snakepit-game with The Unlicense 6 votes vote down vote up
def wshandler(request):
    app = request.app
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    app["sockets"].append(ws)

    while 1:
        msg = await ws.receive()
        if msg.tp == web.MsgType.text:
            print("Got message %s" % msg.data)
            ws.send_str("Pressed key code: {}".format(msg.data))
        elif msg.tp == web.MsgType.close or\
             msg.tp == web.MsgType.error:
            break

    app["sockets"].remove(ws)
    print("Closed connection")
    return ws 
Example #7
Source File: rpc.py    From natrium-wallet-server with MIT License 5 votes vote down vote up
def rpc_reconnect(self, ws : web.WebSocketResponse, r : web.Response, account : str):
        """When a websocket connection sends a subscribe request, do this reconnection step"""
        log.server_logger.info('reconnecting;' + self.util.get_request_ip(r) + ';' + ws.id)

        rpc = {
            "action":"account_info",
            "account":account,
            "pending":True,
            "representative": True
        }
        log.server_logger.info('sending account_info %s', account)
        response = await self.json_post(rpc)

        if response is None:
            log.server_logger.error('reconnect error; %s ; %s', self.util.get_request_ip(r), ws.id)
            ws.send_str('{"error":"reconnect error"}')
        else:
            log.server_logger.debug('received response for account_info %s', json.dumps(response))     
            if account in r.app['subscriptions']:
                r.app['subscriptions'][account].add(ws.id)
            else:
                r.app['subscriptions'][account] = set()
                r.app['subscriptions'][account].add(ws.id)
            r.app['cur_prefs'][ws.id] = await r.app['rdata'].hget(ws.id, "currency")
            await r.app['rdata'].hset(ws.id, "last-connect", float(time.time()))
            price_cur = await r.app['rdata'].hget("prices", f"{self.price_prefix}-" + r.app['cur_prefs'][ws.id].lower())
            price_btc = await r.app['rdata'].hget("prices", f"{self.price_prefix}-btc")
            response['currency'] = r.app['cur_prefs'][ws.id].lower()
            response['price'] = float(price_cur)
            response['btc'] = float(price_btc)
            if self.banano_mode:
                response['nano'] = float(await r.app['rdata'].hget("prices", f"{self.price_prefix}-nano"))
            response['pending_count'] = await self.get_pending_count(r, account, uid = ws.id)
            response = json.dumps(response)

            log.server_logger.info(
                'reconnect response sent ; %s bytes; %s; %s', str(len(response)), self.util.get_request_ip(r), ws.id)

            await ws.send_str(response) 
Example #8
Source File: web_interface.py    From style_transfer with MIT License 5 votes vote down vote up
def handle_websocket(request):
    app = request.app
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    app.wss.append(ws)

    async for _ in ws:
        pass

    try:
        app.wss.remove(ws)
    except ValueError:
        pass

    return ws 
Example #9
Source File: dpow_server.py    From nano-dpow with MIT License 5 votes vote down vote up
def service_ws_handler(self, request):
        ws = web.WebSocketResponse(heartbeat=20.0, max_msg_size=2048)
        await ws.prepare(request)

        try:
            async for msg in ws:
                request_id = None
                if msg.type == WSMsgType.TEXT:
                    try:
                        data = ujson.loads(msg.data)
                        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 
Example #10
Source File: handlers.py    From axibot with GNU General Public License v2.0 5 votes vote down vote up
def client_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    app = request.app

    log.info("Client connected.")
    clients = app['clients']
    clients.add(ws)

    notify_state(app, specific_client=ws)

    try:
        async for raw_msg in ws:
            if raw_msg.tp == aiohttp.MsgType.text:
                msg = api.Message.deserialize(raw_msg.data)
                log.info("User message: %s", msg)
                await handle_user_message(app, ws, msg)
            elif raw_msg.tp == aiohttp.MsgType.closed:
                break
            elif raw_msg.tp == aiohttp.MsgType.error:
                log.info("User websocket error: %s", raw_msg)
                break
            else:
                log.error("Unknown user message type: %s, ignoring.",
                          raw_msg.tp)
    finally:
        log.info("Client connection closed.")
        clients.remove(ws)

    return ws 
Example #11
Source File: appv2.py    From code-jam-5 with MIT License 5 votes vote down vote up
def wshandle(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    async for msg in ws:
        if msg.type == web.WSMsgType.text:
            await ws.send_str(f'received, {msg.data}')
        elif msg.type == web.WSMsgType.binary:
            await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.close:
            break
        if msg.data:
            await bot.channel.send(msg.data)
    return ws 
Example #12
Source File: websocket_server.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def websocket_handler(request):
    """Handle a new socket connection."""

    logger.debug('New websocket connection.')
    websocket = web.WebSocketResponse()
    yield from websocket.prepare(request)
    uuid = uuid4()
    request.app['dispatcher'].subscribe(uuid, websocket)

    while True:
        # Consume input buffer
        try:
            msg = yield from websocket.receive()
        except RuntimeError as e:
            logger.debug('Websocket exception: %s', str(e))
            break
        except CancelledError:
            logger.debug('Websocket closed')
            break
        if msg.type == aiohttp.WSMsgType.CLOSED:
            logger.debug('Websocket closed')
            break
        elif msg.type == aiohttp.WSMsgType.ERROR:
            logger.debug('Websocket exception: %s', websocket.exception())
            break

    request.app['dispatcher'].unsubscribe(uuid)
    return websocket 
Example #13
Source File: websocket_server.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def websocket_handler(request):
    """Handle a new socket connection."""

    logger.debug('New websocket connection.')
    websocket = web.WebSocketResponse()
    yield from websocket.prepare(request)
    uuid = uuid4()
    request.app['dispatcher'].subscribe(uuid, websocket)

    while True:
        # Consume input buffer
        try:
            msg = yield from websocket.receive()
        except RuntimeError as e:
            logger.debug('Websocket exception: %s', str(e))
            break
        except CancelledError:
            logger.debug('Websocket closed')
            break
        if msg.type == aiohttp.WSMsgType.CLOSED:
            logger.debug('Websocket closed')
            break
        elif msg.type == aiohttp.WSMsgType.ERROR:
            logger.debug('Websocket exception: %s', websocket.exception())
            break

    request.app['dispatcher'].unsubscribe(uuid)
    return websocket 
Example #14
Source File: websocket_server.py    From bigchaindb with Apache License 2.0 5 votes vote down vote up
def websocket_handler(request):
    """Handle a new socket connection."""

    logger.debug('New websocket connection.')
    websocket = web.WebSocketResponse()
    yield from websocket.prepare(request)
    uuid = uuid4()
    request.app['dispatcher'].subscribe(uuid, websocket)

    while True:
        # Consume input buffer
        try:
            msg = yield from websocket.receive()
        except RuntimeError as e:
            logger.debug('Websocket exception: %s', str(e))
            break
        except CancelledError:
            logger.debug('Websocket closed')
            break
        if msg.type == aiohttp.WSMsgType.CLOSED:
            logger.debug('Websocket closed')
            break
        elif msg.type == aiohttp.WSMsgType.ERROR:
            logger.debug('Websocket exception: %s', websocket.exception())
            break

    request.app['dispatcher'].unsubscribe(uuid)
    return websocket 
Example #15
Source File: conftest.py    From hass-nabucasa with GNU General Public License v3.0 5 votes vote down vote up
def ws_server(aiohttp_client):
    """Create a mock WS server to connect to and returns a connected client."""

    async def create_client_to_server(handle_server_msg):
        """Create a websocket server."""
        logger = logging.getLogger(f"{__name__}.ws_server")

        async def websocket_handler(request):

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

            async for msg in ws:
                logger.debug("Received msg: %s", msg)
                try:
                    resp = await handle_server_msg(msg)
                    if resp is not None:
                        logger.debug("Sending msg: %s", msg)
                        await ws.send_json(resp)
                except DisconnectMockServer:
                    logger.debug("Closing connection (via DisconnectMockServer)")
                    await ws.close()

            return ws

        app = web.Application()
        app.add_routes([web.get("/ws", websocket_handler)])
        client = await aiohttp_client(app)
        return await client.ws_connect("/ws")

    return create_client_to_server 
Example #16
Source File: service.py    From lbry-sdk with MIT License 5 votes vote down vote up
def log(self, request):
        web_socket = WebSocketResponse()
        await web_socket.prepare(request)
        self.app['websockets'].add(web_socket)
        try:
            async for msg in web_socket:
                if msg.type == WSMsgType.TEXT:
                    if msg.data == 'close':
                        await web_socket.close()
                elif msg.type == WSMsgType.ERROR:
                    print('web socket connection closed with exception %s' %
                          web_socket.exception())
        finally:
            self.app['websockets'].remove(web_socket)
        return web_socket 
Example #17
Source File: webserver.py    From Learning-Concurrency-in-Python with MIT License 5 votes vote down vote up
def wshandler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async for msg in ws:
        if msg.type == web.MsgType.text:
            await ws.send_str("Hello, {}".format(msg.data))
        elif msg.type == web.MsgType.binary:
            await ws.send_bytes(msg.data)
        elif msg.type == web.MsgType.close:
            break

    return ws 
Example #18
Source File: websocket.py    From lbry-sdk with MIT License 5 votes vote down vote up
def on_connect(self, request):
        web_socket = WebSocketResponse()
        await web_socket.prepare(request)
        self.app['websockets'].add(web_socket)
        try:
            async for msg in web_socket:
                if msg.type == WSMsgType.TEXT:
                    await self.on_status(None)
                elif msg.type == WSMsgType.ERROR:
                    print('web socket connection closed with exception %s' %
                          web_socket.exception())
        finally:
            self.app['websockets'].discard(web_socket)
        return web_socket 
Example #19
Source File: fake_cloud_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def get_ws(self, request):
        self.ws = web.WebSocketResponse()
        await self.ws.prepare(request)
        async for msg in self.ws:
            if msg.tp == web.WSMsgType.CLOSE:  # pragma: no cover
                await msg.close()

        return self.ws 
Example #20
Source File: test_connection.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def connection_close_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    await asyncio.sleep(5)

    return ws 
Example #21
Source File: test_connection.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def handler(self, request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)
        async for msg in ws:
            await ws.send_str(msg)

        return ws 
Example #22
Source File: test_connection.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def handler(self, request):
        ws = web.WebSocketResponse(autoping=False)

        await ws.prepare(request)
        async for msg in ws:
            pass
        await asyncio.sleep(1)
        return ws 
Example #23
Source File: test_connection.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def handler(self, request):
        ws = web.WebSocketResponse()
        ensure_future(self.close_server(ws))
        await ws.prepare(request)
        async for msg in ws:
            pass
        return ws 
Example #24
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def websocket_handler(self, request):
        self.ws = web.WebSocketResponse()
        await self.ws.prepare(request)
        async for msg in self.ws:
            await asyncio.sleep(2)

        return self.ws 
Example #25
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def websocket_handler(self, request):
        ws = web.WebSocketResponse()
        self.connections.append(ws)
        await ws.prepare(request)
        ws.send_bytes(b"abc")
        await asyncio.sleep(2)
        print("websocket connection closed")

        return ws 
Example #26
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def recover_handler(self, request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)
        ws.send_bytes(b"abc")

        await asyncio.sleep(2)

        ws.send_bytes(b"resumed") 
Example #27
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def no_pong_handler(self, request):
        ws = web.WebSocketResponse(autoping=False)
        self.connections.append(ws)
        await ws.prepare(request)
        await asyncio.sleep(20)
        return ws 
Example #28
Source File: fake_hmip_server.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def server_shutdown(self, request):
        ws = web.WebSocketResponse()
        self.connections.append(ws)
        await ws.prepare(request)
        self.loop.create_task(self.stop())
        await asyncio.sleep(10)
        # await self.stop()
        return ws 
Example #29
Source File: aiohttp.py    From python-engineio with MIT License 5 votes vote down vote up
def __call__(self, environ):
        request = environ['aiohttp.request']
        self._sock = WebSocketResponse()
        await self._sock.prepare(request)

        self.environ = environ
        await self.handler(self)
        return self._sock 
Example #30
Source File: app.py    From graphql-ws with MIT License 5 votes vote down vote up
def subscriptions(request):
    ws = web.WebSocketResponse(protocols=('graphql-ws',))
    await ws.prepare(request)

    await subscription_server.handle(ws)
    return ws