Server: client_handler, parse_client_message
This commit is contained in:
parent
e99406ea63
commit
0465e66ee9
|
|
@ -7,16 +7,30 @@ import asyncio
|
|||
import websockets
|
||||
|
||||
|
||||
async def hello(websocket, path):
|
||||
name = await websocket.recv()
|
||||
print(f"< {name}")
|
||||
async def parse_client_message(websocket, message_text):
|
||||
"""Parse a message (JSON object) from a client."""
|
||||
|
||||
greeting = f"Hello {name}!"
|
||||
# TODO parse JSON
|
||||
response = f"Hello {message_text}!"
|
||||
|
||||
await websocket.send(greeting)
|
||||
print(f"> {greeting}")
|
||||
await websocket.send(response)
|
||||
print(f"> {response}")
|
||||
|
||||
start_server = websockets.serve(hello, '0.0.0.0', 32715)
|
||||
|
||||
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()
|
||||
|
|
|
|||
Loading…
Reference in New Issue