为什么我们在 signalR 中发生重新连接时检查 context.connectionId?

Why are we checking context.connectionId when a recconect in signalR occurs?

据我所知,对于给定客户端,SignalR Hub 中的 OnReconnected 事件处理程序可以在 OnConnected 之后直接执行,但不能在 OnDisconnected 之后执行。 (来源:http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events

所以,如果 onReconnected 在 onDisconnected 之后永远不会发生并且 context.connectionId 将保持不变,为什么官方示例会检查用户连接中的 context.connectionId 并在不存在时添加它。

Link: http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections

  public override Task OnDisconnected(bool stopCalled)
        {
            string name = Context.User.Identity.Name;

            _connections.Remove(name, Context.ConnectionId);

            return base.OnDisconnected(stopCalled);
        }

如果正常断开连接,stopCalled 将为真。否则,它将是错误的(超时等),但这并不意味着信号器肯定断开连接。

If SignalR is behind a load balancer with scaleout configured, the client may still be connected to another SignalR server.

即使客户端没有断开连接,OnDisconnected(false)也可以触发。然后你删除 Context.ConnectionId.

但是如果客户端仍然处于连接状态,则会触发重新连接。所以那个时候你应该检查你是否删除了这个与 OnDisconnected(false) 的连接,这不是真正的断开连接。