aiohttp.web.WebSocketResponse

Here are the examples of the python api aiohttp.web.WebSocketResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

100 Examples 7

Page 1 Selected Page 2

Example 1

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_start_invalid_method(make_request):
    req = make_request('POST', '/')
    ws = WebSocketResponse()
    with pytest.raises(HTTPMethodNotAllowed):
        yield from ws.prepare(req)

Example 2

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_client_disconnected(make_request, loop, reader):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    exc = errors.ClientDisconnectedError()
    res = helpers.create_future(loop)
    res.set_exception(exc)
    reader.read = make_mocked_coro(res)

    msg = yield from ws.receive()
    assert ws.closed
    assert msg.type == WSMsgType.CLOSE
    assert msg.type is msg.tp
    assert msg.data is None
    assert ws.exception() is None

Example 3

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_cancelled(make_request, loop, reader):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    res = helpers.create_future(loop)
    res.set_exception(asyncio.CancelledError())
    reader.read = make_mocked_coro(res)

    with pytest.raises(asyncio.CancelledError):
        yield from ws.receive()

Example 4

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_ping_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.ping()

Example 5

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_bytes_nonsbytes(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    @asyncio.coroutine
    def receive():
        return WSMessage(WSMsgType.TEXT, 'data', b'')

    ws.receive = receive

    with pytest.raises(TypeError):
        yield from ws.receive_bytes()

Example 6

Project: aiohttp
License: View license
Source File: test_web_websocket.py
Function: test_close_idempotent
@asyncio.coroutine
def test_close_idempotent(make_request, writer):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    assert (yield from ws.close(code=1, message='message1'))
    assert ws.closed
    assert not (yield from ws.close(code=2, message='message2'))

Example 7

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_exc_in_reader(make_request, loop, reader):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    exc = ValueError()
    res = helpers.create_future(loop)
    res.set_exception(exc)
    reader.read = make_mocked_coro(res)

    msg = yield from ws.receive()
    assert msg.type == WSMsgType.ERROR
    assert msg.type is msg.tp
    assert msg.data is exc
    assert ws.exception() is exc

Example 8

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_start_without_upgrade(make_request):
    req = make_request('GET', '/',
                       headers=CIMultiDict({}))
    ws = WebSocketResponse()
    with pytest.raises(HTTPBadRequest):
        yield from ws.prepare(req)

Example 9

Project: ZeroServices
License: View license
Source File: realtime.py
Function: handler
    @asyncio.coroutine
    def handler(self, request):
        ws = aiohttp.web.WebSocketResponse()
        ws.start(request)

        while True:
            msg = yield from ws.receive()

            session = Session(ws, None)
            self.sessions.add(session)

            self.process(session, msg.tp, msg)

            print("Status", self.__class__.sessions, self.__class__.rooms)

        return ws

Example 10

Project: aiohttp
License: View license
Source File: background_tasks.py
Function: websocket_handler
async def websocket_handler(request):
    ws = WebSocketResponse()
    await ws.prepare(request)
    request.app['websockets'].append(ws)
    try:
        async for msg in ws:
            print(msg)
            await asyncio.sleep(1)
    finally:
        request.app['websockets'].remove(ws)
    return ws

Example 11

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_send_bytes_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.send_bytes(b'bytes')

Example 12

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_send_bytes_nonbytes(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    with pytest.raises(TypeError):
        ws.send_bytes('string')

Example 13

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_send_json_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.send_json({'type': 'json'})

Example 14

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_pong_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.pong()

Example 15

Project: snakepit-game
License: View license
Source File: game_loop_basic.py
Function: ws_handler
async 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 16

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_write_eof_not_started():

    ws = WebSocketResponse()
    with pytest.raises(RuntimeError):
        yield from ws.write_eof()

Example 17

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_write_eof_idempotent(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()

    yield from ws.write_eof()
    yield from ws.write_eof()
    yield from ws.write_eof()

Example 18

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_timeouterror(make_request, loop, reader):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    res = helpers.create_future(loop)
    res.set_exception(asyncio.TimeoutError())
    reader.read = make_mocked_coro(res)

    with pytest.raises(asyncio.TimeoutError):
        yield from ws.receive()

Example 19

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_send_str_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.send_str('string')

Example 20

Project: aiohttp
License: View license
Source File: test_web_websocket.py
def test_start_twice_idempotent(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    with pytest.warns(DeprecationWarning):
        impl1 = ws.start(req)
        impl2 = ws.start(req)
        assert impl1 is impl2

Example 21

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_nonstarted_receive_bytes():

    ws = WebSocketResponse()
    with pytest.raises(RuntimeError):
        yield from ws.receive_bytes()

Example 22

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_receive_str_nonstring(make_request):

    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    @asyncio.coroutine
    def receive():
        return WSMessage(WSMsgType.BINARY, b'data', b'')

    ws.receive = receive

    with pytest.raises(TypeError):
        yield from ws.receive_str()

Example 23

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_concurrent_receive(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    ws._waiting = True

    with pytest.raises(RuntimeError):
        yield from ws.receive()

Example 24

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_send_str_nonstring(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    with pytest.raises(TypeError):
        ws.send_str(b'bytes')

Example 25

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_nonstarted_receive_str():

    ws = WebSocketResponse()
    with pytest.raises(RuntimeError):
        yield from ws.receive_str()

Example 26

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_multiple_receive_on_close_connection(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()

    yield from ws.receive()
    yield from ws.receive()
    yield from ws.receive()
    yield from ws.receive()

    with pytest.raises(RuntimeError):
        yield from ws.receive()

Example 27

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_send_json_nonjson(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    with pytest.raises(TypeError):
        ws.send_json(set())

Example 28

Project: aiohttp
License: View license
Source File: test_web_websocket.py
Function: test_close_exc2
@asyncio.coroutine
def test_close_exc2(make_request):

    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)

    exc = ValueError()
    ws._writer = mock.Mock()
    ws._writer.close.side_effect = exc

    yield from ws.close()
    assert ws.closed
    assert ws.exception() is exc

    ws._closed = False
    ws._writer.close.side_effect = asyncio.CancelledError()
    with pytest.raises(asyncio.CancelledError):
        yield from ws.close()

Example 29

Project: Flask-aiohttp
License: View license
Source File: __init__.py
    @property
    def ws(self) -> aiohttp.web.WebSocketResponse:
        """Websocket response of aiohttp"""

        ws = request.environ.get('wsgi.websocket', None)
        if ws is None:
            raise RuntimeError('Request context is not a WebSocket context.')
        return ws

Example 30

Project: aiohttp
License: View license
Source File: test_web_websocket.py
@asyncio.coroutine
def test_can_prepare_started(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    with pytest.raises(RuntimeError) as ctx:
        ws.can_prepare(req)

    assert 'Already started' in str(ctx.value)

Example 31

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
Function: test_send_recv_text
@asyncio.coroutine
def test_send_recv_text(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_str()
        ws.send_str(msg+'/answer')
        yield from ws.close()
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')
    resp.send_str('ask')

    data = yield from resp.receive_str()
    assert data == 'ask/answer'
    yield from resp.close()

Example 32

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
@asyncio.coroutine
def test_send_recv_bytes_bad_type(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_str()
        ws.send_str(msg+'/answer')
        yield from ws.close()
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')
    resp.send_str('ask')

    with pytest.raises(TypeError):
        yield from resp.receive_bytes()
    yield from resp.close()

Example 33

@asyncio.coroutine
def test_send_recv_bytes(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_bytes()
        ws.send_bytes(msg+b'/answer')
        yield from ws.close()
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')

    resp.send_bytes(b'ask')

    data = yield from resp.receive_bytes()
    assert data == b'ask/answer'

    yield from resp.close()

Example 34

Project: sockjs
License: View license
Source File: rawwebsocket.py
Function: process
    @asyncio.coroutine
    def process(self):
        # start websocket connection
        ws = self.ws = web.WebSocketResponse()
        yield from ws.prepare(self.request)

        try:
            yield from self.manager.acquire(self.session)
        except:  # should use specific exception
            yield from ws.close(message='Go away!')
            return ws

        server = ensure_future(self.server(ws, self.session), loop=self.loop)
        client = ensure_future(self.client(ws, self.session), loop=self.loop)
        try:
            yield from asyncio.wait(
                (server, client),
                loop=self.loop,
                return_when=asyncio.FIRST_COMPLETED)
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            yield from self.session._remote_close(exc)
        finally:
            yield from self.manager.release(self.session)
            if not server.done():
                server.cancel()
            if not client.done():
                client.cancel()

        return ws

Example 35

Project: snakepit-game
License: View license
Source File: game_loop_global.py
async def wshandler(request):
    app = request.app
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    if app["game_loop"] is None or \
       app["game_loop"].cancelled():
        app["game_loop"] = asyncio.ensure_future(game_loop(app))
        # this is required to propagate exceptions
        app["game_loop"].add_done_callback(lambda t: t.result()
                                           if not t.cancelled() else None)
    app["sockets"].append(ws)
    while 1:
        msg = await ws.receive()
        if msg.tp == web.MsgType.text:
            ws.send_str("Pressed key code: {}".format(msg.data))
            print("Got message %s" % msg.data)
        elif msg.tp == web.MsgType.close or\
             msg.tp == web.MsgType.error:
            break

    app["sockets"].remove(ws)

    if len(app["sockets"]) == 0:
        print("Stopping game loop")
        app["game_loop"].cancel()

    print("Closed connection")
    return ws

Example 36

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
@asyncio.coroutine
def test_send_recv_text_bad_type(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_bytes()
        ws.send_bytes(msg+b'/answer')
        yield from ws.close()
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')

    resp.send_bytes(b'ask')

    with pytest.raises(TypeError):
        yield from resp.receive_str()

    yield from resp.close()

Example 37

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
Function: test_send_recv_json
@asyncio.coroutine
def test_send_recv_json(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        data = yield from ws.receive_json()
        ws.send_json({'response': data['request']})
        yield from ws.close()
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')
    payload = {'request': 'test'}
    resp.send_json(payload)

    data = yield from resp.receive_json()
    assert data['response'] == payload['request']
    yield from resp.close()

Example 38

Project: snakepit-game
License: View license
Source File: game_loop_handler.py
async 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 39

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
@asyncio.coroutine
def test_ping_pong(loop, test_client):

    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_bytes()
        ws.ping()
        ws.send_bytes(msg+b'/answer')
        try:
            yield from ws.close()
        finally:
            closed.set_result(1)
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')

    resp.ping()
    resp.send_bytes(b'ask')

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.BINARY
    assert msg.data == b'ask/answer'

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE

    yield from resp.close()
    yield from closed

Example 40

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
@asyncio.coroutine
def test_ping_pong_manual(loop, test_client):

    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_bytes()
        ws.ping()
        ws.send_bytes(msg+b'/answer')
        try:
            yield from ws.close()
        finally:
            closed.set_result(1)
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/', autoping=False)

    resp.ping()
    resp.send_bytes(b'ask')

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.PONG

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.PING
    resp.pong()

    msg = yield from resp.receive()
    assert msg.data == b'ask/answer'

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE

    yield from closed

Example 41

Project: aiohttp_runserver
License: View license
Source File: serve.py
Function: websocket_handler
async def websocket_handler(request):
    ws = web.WebSocketResponse()
    url = None
    await ws.prepare(request)
    ws_type_lookup = {k.value: v for v, k in MsgType.__members__.items()}

    async for msg in ws:
        if msg.tp == MsgType.text:
            try:
                data = json.loads(msg.data)
            except json.JSONDecodeError as e:
                aux_logger.error('JSON decode error: %s', str(e))
            else:
                command = data['command']
                if command == 'hello':
                    if 'http://livereload.com/protocols/official-7' not in data['protocols']:
                        aux_logger.error('live reload protocol 7 not supported by client %s', msg.data)
                        ws.close()
                    else:
                        handshake = {
                            'command': 'hello',
                            'protocols': [
                                'http://livereload.com/protocols/official-7',
                            ],
                            'serverName': 'livereload-aiohttp',
                        }
                        ws.send_str(json.dumps(handshake))
                elif command == 'info':
                    aux_logger.debug('browser connected: %s', data)
                    url = data['url'].split('/', 3)[-1]
                    request.app[WS].append((ws, url))
                else:
                    aux_logger.error('Unknown ws message %s', msg.data)
        elif msg.tp == MsgType.error:
            aux_logger.error('ws connection closed with exception %s',  ws.exception())
        else:
            aux_logger.error('unknown websocket message type %s, data: %s', ws_type_lookup[msg.tp], msg.data)

    aux_logger.debug('browser disconnected')
    if url:
        request.app[WS].remove((ws, url))
    return ws

Example 42

Project: sockjs
License: View license
Source File: websocket.py
Function: process
    @asyncio.coroutine
    def process(self):
        # start websocket connection
        ws = self.ws = web.WebSocketResponse()
        yield from ws.prepare(self.request)

        # session was interrupted
        if self.session.interrupted:
            self.ws.send_str(close_frame(1002, 'Connection interrupted'))

        elif self.session.state == STATE_CLOSED:
            self.ws.send_str(close_frame(3000, 'Go away!'))

        else:
            try:
                yield from self.manager.acquire(self.session)
            except:  # should use specific exception
                self.ws.send_str(close_frame(3000, 'Go away!'))
                yield from ws.close()
                return ws

            server = ensure_future(
                self.server(ws, self.session), loop=self.loop)
            client = ensure_future(
                self.client(ws, self.session), loop=self.loop)
            try:
                yield from asyncio.wait(
                    (server, client),
                    loop=self.loop,
                    return_when=asyncio.FIRST_COMPLETED)
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                yield from self.session._remote_close(exc)
            finally:
                yield from self.manager.release(self.session)
                if not server.done():
                    server.cancel()
                if not client.done():
                    client.cancel()

        return ws

Example 43

Project: snakepit-game
License: View license
Source File: game_loop_process.py
async def wshandler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    recv_task = None
    tick_task = None
    while 1:
        if not recv_task:
            recv_task = asyncio.ensure_future(ws.receive())
        if not tick_task:
            await tick.acquire()
            tick_task = asyncio.ensure_future(tick.wait())

        done, pending = await asyncio.wait(
            [recv_task,
             tick_task],
            return_when=asyncio.FIRST_COMPLETED)

        if recv_task in done:
            msg = recv_task.result()
            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
            recv_task = None

        if tick_task in done:
            ws.send_str("game loop ticks")
            tick.release()
            tick_task = None

    return ws

Example 44

Project: aiohttp
License: View license
Source File: test_client_ws_functional.py
Function: test_close
@asyncio.coroutine
def test_close(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        yield from ws.receive_bytes()
        ws.send_str('test')

        yield from ws.receive()
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')

    resp.send_bytes(b'ask')

    closed = yield from resp.close()
    assert closed
    assert resp.closed
    assert resp.close_code == 1000

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSED

Example 45

Project: aiohttp
License: View license
Source File: views.py
Function: index
async def index(request):
    resp = web.WebSocketResponse()
    ok, protocol = resp.can_start(request)
    if not ok:
        return aiohttp_jinja2.render_template('index.html', request, {})

    await resp.prepare(request)
    name = (random.choice(string.ascii_uppercase) +
            ''.join(random.sample(string.ascii_lowercase*10, 10)))
    log.info('%s joined.', name)
    resp.send_str(json.dumps({'action': 'connect',
                              'name': name}))
    for ws in request.app['sockets'].values():
        ws.send_str(json.dumps({'action': 'join',
                                'name': name}))
    request.app['sockets'][name] = resp

    while True:
        msg = await resp.receive()

        if msg.type == web.MsgType.text:
            for ws in request.app['sockets'].values():
                if ws is not resp:
                    ws.send_str(json.dumps({'action': 'sent',
                                            'name': name,
                                            'text': msg.data}))
        else:
            break

    del request.app['sockets'][name]
    log.info('%s disconnected.', name)
    for ws in request.app['sockets'].values():
        ws.send_str(json.dumps({'action': 'disconnect',
                                'name': name}))
    return resp

Example 46

Project: aiohttp
License: View license
Source File: web_ws.py
Function: ws_handler
async def wshandler(request):
    resp = WebSocketResponse()
    ok, protocol = resp.can_prepare(request)
    if not ok:
        with open(WS_FILE, 'rb') as fp:
            return Response(body=fp.read(), content_type='text/html')

    await resp.prepare(request)

    try:
        print('Someone joined.')
        for ws in request.app['sockets']:
            ws.send_str('Someone joined')
        request.app['sockets'].append(resp)

        async for msg in resp:
            if msg.type == WSMsgType.TEXT:
                for ws in request.app['sockets']:
                    if ws is not resp:
                        ws.send_str(msg.data)
            else:
                return resp
        return resp

    finally:
        request.app['sockets'].remove(resp)
        print('Someone disconnected.')
        for ws in request.app['sockets']:
            ws.send_str('Someone disconnected.')

Example 47

Project: aiohttp-devtools
License: View license
Source File: serve.py
async def websocket_handler(request):
    ws = web.WebSocketResponse(timeout=0.01)
    url = None
    await ws.prepare(request)

    async for msg in ws:
        if msg.tp == WSMsgType.TEXT:
            try:
                data = json.loads(msg.data)
            except json.JSONDecodeError as e:
                logger.error('JSON decode error: %s', str(e))
            else:
                command = data['command']
                if command == 'hello':
                    if 'http://livereload.com/protocols/official-7' not in data['protocols']:
                        logger.error('live reload protocol 7 not supported by client %s', msg.data)
                        ws.close()
                    else:
                        handshake = {
                            'command': 'hello',
                            'protocols': [
                                'http://livereload.com/protocols/official-7',
                            ],
                            'serverName': 'livereload-aiohttp',
                        }
                        ws.send_str(json.dumps(handshake))
                elif command == 'info':
                    logger.debug('browser connected: %s', data)
                    url = '/' + data['url'].split('/', 3)[-1]
                    request.app[WS].append((ws, url))
                else:
                    logger.error('Unknown ws message %s', msg.data)
        elif msg.tp == WSMsgType.ERROR:
            logger.error('ws connection closed with exception %s', ws.exception())
        else:
            logger.error('unknown websocket message type %s, data: %s', WS_TYPE_LOOKUP[msg.tp], msg.data)

    if url is None:
        logger.warning('browser disconnected, appears no websocket connection was made')
    else:
        logger.debug('browser disconnected')
        request.app[WS].remove((ws, url))
    return ws

Example 48

Project: aioreactive
License: View license
Source File: autocomplete.py
async def websocket_handler(request):
    print("WebSocket opened")

    stream = AsyncStream()

    # Line break before binary operator is more readable. Disable W503
    xs = (stream
          | op.map(lambda x: x["term"])
          | op.filter(lambda text: len(text) > 2)
          | op.debounce(0.75)
          | op.distinct_until_changed()
          | op.map(search_wikipedia)
          | op.switch_latest()
          )

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

    async def asend(value):
        ws.send_str(value)

    async def athrow(ex):
        print(ex)

    await start(xs, FuncSink(asend, athrow))

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            obj = json.loads(msg.data)
            await stream.asend(obj)

        elif msg.type == aiohttp.WSMsgType.ERROR:
            print('ws connection closed with exception %s' % ws.exception())

    print('websocket connection closed')
    return ws

Example 49

Project: snakepit-game
License: View license
Source File: server.py
async def wshandler(request):
    print("Connected")
    app = request.app
    game = app["game"]
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    player = None
    while True:
        msg = await ws.receive()
        if msg.tp == web.MsgType.text:
            print("Got message %s" % msg.data)

            data = json.loads(msg.data)
            if type(data) == int and player:
                # Interpret as key code
                player.keypress(data)
            if type(data) != list:
                continue
            if not player:
                if data[0] == "new_player":
                    player = game.new_player(data[1], ws)
            elif data[0] == "join":
                if not game.running:
                    game.reset_world()

                    print("Starting game loop")
                    asyncio.ensure_future(game_loop(game))

                game.join(player)

        elif msg.tp == web.MsgType.close:
            break

    if player:
        game.player_disconnected(player)

    print("Closed connection")
    return ws

Example 50

Project: aiohttp
License: View license
Source File: server.py
Function: ws_handler
@asyncio.coroutine
def wshandler(request):
    ws = web.WebSocketResponse(autoclose=False)
    ok, protocol = ws.can_start(request)
    if not ok:
        return web.HTTPBadRequest()

    yield from ws.prepare(request)

    while True:
        msg = yield from ws.receive()

        if msg.type == web.MsgType.text:
            ws.send_str(msg.data)
        elif msg.type == web.MsgType.binary:
            ws.send_bytes(msg.data)
        elif msg.type == web.MsgType.close:
            yield from ws.close()
            break
        else:
            break

    return ws
See More Examples - Go to Next Page
Page 1 Selected Page 2