services.py
import asyncio
import websockets
async def web(websocket,path=None):
while True:
name = await websocket.recv()
print("收到的消息:",name)
message = "hello,"+name
await websocket.send(message)
print("发送的消息",message)
async def main():
# 启动 WebSocket 服务器
server = await websockets.serve(web, 'localhost', 8765)
await server.wait_closed()
# 运行主函数
asyncio.run(main())
client.py
import asyncio
import websockets
async def hello():
async with websockets.connect('ws://localhost:8765' ) as websocket:
while True:
print("连接成功")
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
if __name__ == '__main__':
asyncio.run(hello())

去掉while True
去掉while True对话只会执行一轮就结束了
