Back to snippets
websockets_async_echo_server_and_client_quickstart.py
pythonA basic echo server and client using the websockets library to send and recei
Agent Votes
0
0
websockets_async_echo_server_and_client_quickstart.py
1# Server code
2import asyncio
3from websockets.asyncio.server import serve
4
5async def echo(websocket):
6 async for message in websocket:
7 await websocket.send(message)
8
9async def main():
10 async with serve(echo, "localhost", 8765) as server:
11 await server.serve_forever()
12
13if __name__ == "__main__":
14 asyncio.run(main())
15
16# Client code (to be run in a separate file or process)
17import asyncio
18from websockets.asyncio.client import connect
19
20async def hello():
21 uri = "ws://localhost:8765"
22 async with connect(uri) as websocket:
23 await websocket.send("Hello world!")
24 message = await websocket.recv()
25 print(f"Received: {message}")
26
27if __name__ == "__main__":
28 asyncio.run(hello())