保持SignalR客户端连接活着

时间:2016-06-24 17:54:49

标签: websocket signalr signalr.client

如果我的SignalR客户端连接断开,我希望客户端尝试重新连接。这是实现这个的好模式吗?我指的是通过重新启动连接来处理SignalR连接上的Closed事件。

public class OnPremiseWebHubClient
{
    private HubConnection _hubConnection;
    private IHubProxy _hubProxy;

    private OnPremiseWebHubClient() { }
    static OnPremiseWebHubClient() { }
    private static readonly OnPremiseWebHubClient _instance = new OnPremiseWebHubClient();
    public static OnPremiseWebHubClient Instance { get { return _instance; } }

    public async Task Start()
    {
        _hubConnection = new HubConnection("http://OnPremiseWeb/");
        _hubProxy = _hubConnection.CreateHubProxy("OnPremiseHub");

        // IS THIS A GOOD PATTERN FOR KEEPING THE CONNECTION ALIVE?
        _hubConnection.Closed += async () =>
        {
            // reconnect if we close
            await _hubConnection.Start();
        };

        await _hubConnection.Start();
    }
}

1 个答案:

答案 0 :(得分:2)

SignalR拥有自己的重新连接机制。但经过一些重试后,状态将变为断开/已关闭。断开/关闭状态意味着信号器尝试重新连接,但它无法实现。因此,在那里应用重新连接以便不断重新连接是个好地方。

有一个缺点:在移动设备上,重新连接将使用电池。

您可以查看here了解详情。