You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.7 KiB

#!/usr/bin/env python3
"""
简单的WebSocket服务器用于测试
"""
import asyncio
import websockets
import json
from datetime import datetime
async def echo_handler(websocket, path):
"""简单的echo处理器"""
print(f"客户端连接: {websocket.remote_address}")
try:
async for message in websocket:
print(f"收到消息: {message}")
# 解析消息
try:
data = json.loads(message)
message_type = data.get("type", "unknown")
# 处理心跳
if message_type == "heartbeat":
response = {
"type": "heartbeat",
"data": {"Message": "pong"},
"timestamp": datetime.now().isoformat()
}
else:
# Echo消息
response = {
"type": "echo",
"data": data.get("data", message),
"timestamp": datetime.now().isoformat()
}
# 发送响应
await websocket.send(json.dumps(response))
print(f"发送响应: {response}")
except json.JSONDecodeError:
# 如果不是JSON,直接echo
await websocket.send(message)
print(f"Echo: {message}")
except websockets.exceptions.ConnectionClosed:
print(f"客户端断开: {websocket.remote_address}")
except Exception as e:
print(f"处理消息时出错: {e}")
# 不要抛出异常,避免服务器崩溃
try:
await websocket.send(json.dumps({
"type": "error",
"data": {"message": str(e)},
"timestamp": datetime.now().isoformat()
}))
except:
pass
async def main():
"""启动WebSocket服务器"""
host = "localhost"
port = 8080
print(f"启动WebSocket服务器: ws://{host}:{port}")
print("按 Ctrl+C 停止服务器")
try:
# 使用更稳定的服务器配置
server = await websockets.serve(
echo_handler,
host,
port,
ping_interval=30, # 30秒ping间隔
ping_timeout=10, # 10秒ping超时
close_timeout=10 # 10秒关闭超时
)
print(f"WebSocket服务器已启动: ws://{host}:{port}")
await server.wait_closed()
except KeyboardInterrupt:
print("\n服务器已停止")
except Exception as e:
print(f"服务器启动失败: {e}")
if __name__ == "__main__":
asyncio.run(main())