File: server.py

package info (click to toggle)
python-aiohttp 3.11.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,156 kB
  • sloc: python: 51,898; ansic: 20,843; makefile: 395; javascript: 31; sh: 3
file content (56 lines) | stat: -rw-r--r-- 1,452 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python3

import logging
from typing import List

from aiohttp import WSCloseCode, web

websockets = web.AppKey("websockets", List[web.WebSocketResponse])


async def wshandler(request: web.Request) -> web.WebSocketResponse:
    ws = web.WebSocketResponse(autoclose=False)
    is_ws = ws.can_prepare(request)
    if not is_ws:
        raise web.HTTPBadRequest()

    await ws.prepare(request)

    request.app[websockets].append(ws)

    while True:
        msg = await ws.receive()

        if msg.type == web.WSMsgType.TEXT:
            await ws.send_str(msg.data)
        elif msg.type == web.WSMsgType.BINARY:
            await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.CLOSE:
            await ws.close()
            break
        else:
            break

    return ws


async def on_shutdown(app: web.Application) -> None:
    ws_list = app[websockets]
    for ws in set(ws_list):
        await ws.close(code=WSCloseCode.GOING_AWAY, message=b"Server shutdown")


if __name__ == "__main__":
    logging.basicConfig(
        level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s"
    )

    app = web.Application()
    l: List[web.WebSocketResponse] = []
    app[websockets] = l
    app.router.add_route("GET", "/", wshandler)
    app.on_shutdown.append(on_shutdown)
    try:
        web.run_app(app, port=9001)
    except KeyboardInterrupt:
        print("Server stopped at http://127.0.0.1:9001")