From cbf90dda4d76bb14bd1d81e0823076e4cde5beee Mon Sep 17 00:00:00 2001 From: retoor Date: Tue, 21 Jan 2025 12:05:05 +0000 Subject: [PATCH] Add how-to-setup-websocket-example.md --- how-to-setup-websocket-example.md | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 how-to-setup-websocket-example.md diff --git a/how-to-setup-websocket-example.md b/how-to-setup-websocket-example.md new file mode 100644 index 0000000..f9f8cc9 --- /dev/null +++ b/how-to-setup-websocket-example.md @@ -0,0 +1,44 @@ +# Setting up a websocket using Python aiohttp + +1. Execute on bash: +``` +sudo apt install python3-env python3-pip -y +python -m venv .venv +``` +2. Copy the following contents to app.py +```python +from aiohttp import web + +app = web.Application() + +async def websocket_handler(request): + + ws = web.WebSocketResponse() + await ws.prepare(request) + + async for msg in ws: + if msg.type == aiohttp.WSMsgType.TEXT: + if msg.data == 'close': + await ws.close() + else: + await ws.send_str(msg.data + '/answer') + elif msg.type == aiohttp.WSMsgType.ERROR: + print('ws connection closed with exception %s' % + ws.exception()) + + print('websocket connection closed') + + return ws + +app.router.add_get("/", websocket_handler) +web.run_app(app,host="0.0.0.0", port=7331) + +3. Execute application +```bash +source .venv/bin/activate +python app.py +``` +or directly without environment active: +```bash +./venv/bin/python app.py +``` \ No newline at end of file