add a python echo server that does not close the connection after each received messages

This commit is contained in:
Benjamin Sergeant 2020-02-26 12:11:31 -08:00
parent 21db7b6c5b
commit 5ce1a596cf
2 changed files with 26 additions and 3 deletions

View File

@ -8,9 +8,10 @@ import websockets
async def echo(websocket, path): async def echo(websocket, path):
msg = await websocket.recv() while True:
print(f'Received {len(msg)} bytes') msg = await websocket.recv()
await websocket.send(msg) print(f'Received {len(msg)} bytes')
await websocket.send(msg)
host = os.getenv('BIND_HOST', 'localhost') host = os.getenv('BIND_HOST', 'localhost')
print(f'Serving on {host}:8766') print(f'Serving on {host}:8766')

View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
# WS server example
import asyncio
import os
import websockets
async def echo(websocket, path):
while True:
msg = await websocket.recv()
print(f'Received {len(msg)} bytes')
await websocket.send(msg)
host = os.getenv('BIND_HOST', 'localhost')
print(f'Serving on {host}:8766')
start_server = websockets.serve(echo, host, 8766, max_size=2 ** 30)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()