| 1 |
#!/usr/bin/env python3 |
| 2 |
"""Example for aiohttp.web websocket server.""" |
| 3 |
|
| 4 |
# The extra strict mypy settings are here to help test that `Application[AppKey()]` |
| 5 |
# syntax is working correctly. A regression will cause mypy to raise an error. |
| 6 |
# mypy: disallow-any-expr, disallow-any-unimported, disallow-subclassing-any |
| 7 |
|
| 8 |
import os |
| 9 |
from typing import List |
| 10 |
|
| 11 |
from aiohttp import web |
| 12 |
|
| 13 |
WS_FILE = os.path.join(os.path.dirname(__file__), "websocket.html") |
| 14 |
sockets = web.AppKey("sockets", List[web.WebSocketResponse]) |
| 15 |
|
| 16 |
|
| 17 |
async def wshandler(request: web.Request) -> web.StreamResponse: |
| 18 |
resp = web.WebSocketResponse() |
| 19 |
available = resp.can_prepare(request) |
| 20 |
if not available: |
| 21 |
with open(WS_FILE, "rb") as fp: |
| 22 |
return web.Response(body=fp.read(), content_type="text/html") |
| 23 |
|
| 24 |
await resp.prepare(request) |
| 25 |
|
| 26 |
await resp.send_str("Welcome!!!") |
| 27 |
|
| 28 |
try: |
| 29 |
print("Someone joined.") |
| 30 |
for ws in request.app[sockets]: |
| 31 |
await ws.send_str("Someone joined") |
| 32 |
request.app[sockets].append(resp) |
| 33 |
|
| 34 |
async for msg in resp: # type: ignore[misc] |
| 35 |
if msg.type == web.WSMsgType.TEXT: # type: ignore[misc] |
| 36 |
for ws in request.app[sockets]: |
| 37 |
if ws is not resp: |
| 38 |
await ws.send_str(msg.data) # type: ignore[misc] |
| 39 |
else: |
| 40 |
return resp |
| 41 |
return resp |
| 42 |
|
| 43 |
finally: |
| 44 |
request.app[sockets].remove(resp) |
| 45 |
print("Someone disconnected.") |
| 46 |
for ws in request.app[sockets]: |
| 47 |
await ws.send_str("Someone disconnected.") |
| 48 |
|
| 49 |
|
| 50 |
async def on_shutdown(app: web.Application) -> None: |
| 51 |
for ws in app[sockets]: |
| 52 |
await ws.close() |
| 53 |
|
| 54 |
|
| 55 |
def init() -> web.Application: |
| 56 |
app = web.Application() |
| 57 |
l: List[web.WebSocketResponse] = [] |
| 58 |
app[sockets] = l |
| 59 |
app.router.add_get("/", wshandler) |
| 60 |
app.on_shutdown.append(on_shutdown) |
| 61 |
return app |
| 62 |
|
| 63 |
|
| 64 |
web.run_app(init()) |