2025-01-21 12:05:05 +00:00
|
|
|
# Setting up a websocket using Python aiohttp
|
|
|
|
|
2025-01-21 12:13:19 +00:00
|
|
|
## About snippet
|
|
|
|
The whole websocket handler is tolen from the original docs.
|
|
|
|
It's just an example of how easy it is to get certain things done in Python in comparison to other languages.
|
|
|
|
|
2025-01-21 12:05:05 +00:00
|
|
|
1. Execute on bash:
|
|
|
|
```
|
|
|
|
sudo apt install python3-env python3-pip -y
|
|
|
|
python -m venv .venv
|
2025-01-21 12:10:19 +00:00
|
|
|
./venv/bin/pip install aiohttp
|
2025-01-21 12:05:05 +00:00
|
|
|
```
|
|
|
|
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)
|
2025-01-21 12:05:47 +00:00
|
|
|
```
|
2025-01-21 12:05:05 +00:00
|
|
|
3. Execute application
|
|
|
|
```bash
|
|
|
|
source .venv/bin/activate
|
|
|
|
python app.py
|
|
|
|
```
|
|
|
|
or directly without environment active:
|
|
|
|
```bash
|
|
|
|
./venv/bin/python app.py
|
|
|
|
```
|