为什么signalR心跳不需要客户端响应

时间:2017-12-26 15:44:02

标签: signalr signalr-hub

SouceCode:https://github.com/SignalR/SignalR/blob/72418317c95182fd8d2f8ba1b69b02bfbb79baaa/src/Microsoft.AspNet.SignalR.Core/Transports/TransportHeartBeat.cs

服务器发送心跳包,然后标记连接,而不等待客户端响应

    private void CheckTimeoutAndKeepAlive(ConnectionMetadata metadata)
    {
        if (RaiseTimeout(metadata))
        {
            // If we're past the expiration time then just timeout the connection
            metadata.Connection.Timeout();
        }
        else
        {
            // The connection is still alive so we need to keep it alive with a server side "ping".
            // This is for scenarios where networking hardware (proxies, loadbalancers) get in the way
            // of us handling timeout's or disconnects gracefully
            if (RaiseKeepAlive(metadata))
            {
                Trace.TraceEvent(TraceEventType.Verbose, 0, "KeepAlive(" + metadata.Connection.ConnectionId + ")");

                // Ensure delegate continues to use the C# Compiler static delegate caching optimization.
                metadata.Connection.KeepAlive().Catch((ex, state) => OnKeepAliveError(ex, state), state: Trace, traceSource: Trace);
            }

            MarkConnection(metadata.Connection);
        }
    }

如何检测客户端已断开连接? 客户端如何检测自身并且服务器已断开连接?

1 个答案:

答案 0 :(得分:0)

基本上,这取决于您的连接类型。 (套接字,LongPolling等。)套接字为您提供TCP / UDP端口连接,并为您提供断开连接的通知。

对于其他类型的连接,心跳或其他有效的方法。 SignalR内核每隔一秒使用一次心跳。因此,SignalR Core可在一秒钟内检测到断开连接。