-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_sever.py
More file actions
27 lines (23 loc) · 956 Bytes
/
web_sever.py
File metadata and controls
27 lines (23 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import asyncio
import websockets
async def handle_client(websocket, path):
print("Client connected")
try:
while True:
# 接收来自客户端的消息
message = await websocket.recv()
print(f"Received message from client: {message}")
# 生成响应并发送回客户端(模拟流式响应)
for i in range(3): # 发送3条消息片段
response = f"Server response part {i+1} to: {message}"
await websocket.send(response)
await asyncio.sleep(1) # 模拟延时
print("Response sent to client")
except websockets.exceptions.ConnectionClosed:
print("Client disconnected")
async def main():
server = await websockets.serve(handle_client, "localhost", 8000)
print("WebSocket server started on ws://localhost:8000")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())