37 lines
955 B
Python
Executable File
37 lines
955 B
Python
Executable File
#!/usr/bin/env python
|
|
|
|
# Example code from:
|
|
# https://websockets.readthedocs.io/en/stable/intro.html
|
|
|
|
import asyncio
|
|
import websockets
|
|
|
|
|
|
async def parse_client_message(websocket, message_text):
|
|
"""Parse a message (JSON object) from a client."""
|
|
|
|
# TODO parse JSON
|
|
response = f"Hello {message_text}!"
|
|
|
|
await websocket.send(response)
|
|
print(f"> {response}")
|
|
|
|
|
|
async def client_handler(websocket, path):
|
|
"""Handle client connection."""
|
|
|
|
print(f"++ New client")
|
|
try:
|
|
# Read and parse messages until connection is closed
|
|
async for message_text in websocket:
|
|
print(f"< {message_text}")
|
|
await parse_client_message(websocket, message_text)
|
|
finally:
|
|
print(f"-- Client connection closed")
|
|
|
|
# Create WebSocket listener
|
|
start_server = websockets.serve(client_handler, '0.0.0.0', 32715)
|
|
|
|
asyncio.get_event_loop().run_until_complete(start_server)
|
|
asyncio.get_event_loop().run_forever()
|