Python与ASP.NET SignalR通信异常:客户端发消息服务端方法未触发
问题解决:Python SignalR客户端发送消息后服务端方法未触发
问题根源分析
从你的日志能看到,客户端发送消息后立刻出现连接关闭错误,核心问题在于:
- 调用
hub_connection.start()后立刻发送消息,此时连接还未完成握手流程,消息发送时机过早 on_open等回调的注册顺序错误,应该在start()之前注册,否则无法正确捕获连接打开事件- 同步调用异步的
start()方法,导致连接状态未就绪就执行后续操作
修复后的Python代码
import logging from signalrcore.hub_connection_builder import HubConnectionBuilder import asyncio class SignalRClient: def __init__(self): self.hub_connection = None async def connect(self): try: self.hub_connection = HubConnectionBuilder() \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }) \ .with_url("https://localhost:7294/WebSocketMessageHub", options={"verify_ssl": False}) \ .build() # 先注册所有回调,再启动连接 self.hub_connection.on("ReceiveMessage", self.receive_message) self.hub_connection.on_open(lambda: print("connection opened and handshake received ready to send messages")) self.hub_connection.on_close(lambda: print("connection closed")) self.hub_connection.on_error(lambda data: print(f"An exception was thrown closed{data.error}")) # 异步等待连接完成 await self.hub_connection.start() print("Connected to SignalR Hub") # 连接打开后再发送消息 await self.hub_connection.send("SendGemstoneDetailMessage", ["dwdw"]) except Exception as e: print(f"Failed to connect to the server: {e}") def receive_message(self, *args, **kwargs): print(f"ITS MEE: {args}") async def listen_forever(self): while True: await asyncio.sleep(1) async def main(): signalr_client = SignalRClient() await signalr_client.connect() await signalr_client.listen_forever() if __name__ == "__main__": asyncio.run(main())
额外检查点
- 服务端Hub方法参数:当前C#的
SendGemstoneDetailMessage方法参数List<string>与客户端发送的["dwdw"]类型匹配,无需调整 - 跨域配置:如果客户端和服务端域名不同,确认ASP.NET Core项目中已正确配置跨域策略,允许SignalR连接
- 服务端日志排查:在C# Hub中添加更多日志,确认连接状态和方法调用情况:
public class WebSocketHub : Hub { private readonly IWebSocketService _webSocketService; public WebSocketHub(IWebSocketService webSocketService) { _webSocketService = webSocketService; } public override Task OnConnectedAsync() { Console.WriteLine($"客户端已连接: {Context.ConnectionId}"); _webSocketService.ConnectAdmin(Context); return base.OnConnectedAsync(); } public async Task SendGemstoneDetailMessage(List<string> messag) { Console.WriteLine($"收到消息: {string.Join(",", messag)}"); Console.WriteLine("HELLO"); // 可选:给客户端返回接收确认 await Clients.Caller.SendAsync("ReceiveMessage", "消息已接收"); } }
关键修改说明
- 将
connect方法改为异步,用await等待start()和send()完成,确保连接就绪后再发送消息 - 调整回调注册顺序,在
start()之前注册on_open等事件,保证能捕获连接状态变化 - 发送消息时使用
await hub_connection.send(),确保消息发送操作完成
内容的提问来源于stack exchange,提问作者Majkelele
相关产品推荐
相关产品推荐

