baoxiang/test_websocket_connect.py
2025-12-16 18:06:50 +08:00

55 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
测试WebSocket连接的脚本
模拟前端连接
"""
import asyncio
import websockets
import json
import sys
import os
# 设置环境变量
os.environ.setdefault('SECRET_KEY', 'your-secret-key-change-in-production')
async def test_streamer_connection():
"""测试主播WebSocket连接"""
# 使用有效的token从日志中复制的
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjYzOTcyMTEsInN1YiI6IjEwIn0.Miublr4D4W5_xS80eNb9mEMQlH-k9fh2Vc4Ndjf8GPQ"
streamer_id = 10
uri = f"ws://localhost:8000/socket.io/?role=streamer&id={streamer_id}&token={token}"
try:
print(f"尝试连接到: {uri}")
async with websockets.connect(uri) as websocket:
print("✅ WebSocket连接成功")
# 等待消息
for i in range(10):
try:
response = await asyncio.wait_for(websocket.recv(), timeout=3.0)
print(f"📥 收到消息 {i+1}: {response}")
except asyncio.TimeoutError:
print(f"⏱️ 3秒内未收到消息 {i+1}(继续等待)")
continue
print("\n✅ 测试完成!")
return True
except websockets.exceptions.InvalidURI as e:
print(f"❌ 无效的URI: {e}")
return False
except websockets.exceptions.ConnectionRefused as e:
print(f"❌ 连接被拒绝: {e}")
return False
except Exception as e:
print(f"❌ 连接错误: {type(e).__name__}: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
result = asyncio.run(test_streamer_connection())
sys.exit(0 if result else 1)