instantchat/server/chatserver.py

37 lines
955 B
Python
Raw Normal View History

2018-10-27 04:36:09 +02:00
#!/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."""
2018-10-27 04:36:09 +02:00
# TODO parse JSON
response = f"Hello {message_text}!"
2018-10-27 04:36:09 +02:00
await websocket.send(response)
print(f"> {response}")
2018-10-27 04:36:09 +02:00
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)
2018-10-27 04:36:09 +02:00
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()