SignalR .Net客户端:如何重新建立连接

pho*_*nix 15 client signalr

我看过这篇文章

在某些应用程序中,您可能希望在连接丢失并且重新连接尝试超时后自动重新建立连接.为此,您可以从Closed事件处理程序(JavaScript客户端上的已断开事件处理程序)调用Start方法.您可能希望在调用Start之前等待一段时间,以避免在服务器或物理连接不可用时过于频繁地执行此操作.以下代码示例适用于使用生成的代理的JavaScript客户端.

当我从Closed事件中调用Start方法时

connection.Closed += connection_Closed;
static void connection_Closed()
    {
        Console.WriteLine("connection closed");
        ServerConnection.Start().Wait();
    }
Run Code Online (Sandbox Code Playgroud)

发生异常:连接尚未建立.

我希望它一直持续到服务器运行正常时才成功.不要抛出异常.我怎么做到这一点.

有任何想法吗?

谢谢

pho*_*nix 10

在.net客户端上,您可以从已关闭的事件处理程序中调用start方法.如果服务器不可用,则应进行递归调用.

例如

_connection.Closed += OnDisconnected;
static void OnDisconnected()
{
    Console.WriteLine("connection closed");
    var t=_connection.Start()

    bool result =false;
    t.ContinueWith(task=>
    {
       if(!task.IsFaulted)
       {
           result = true;
       }
    }).Wait();

    if(!result)
    {
         OnDisconnected();
    }
}
Run Code Online (Sandbox Code Playgroud)


Dun*_*unc 9

与凤凰答案的不同之处:

  • OnDisconnected由于Closed在连接失败时触发了事件,因此实际上不需要显式调用
  • 重试之前的小延迟
  • 每次重新创建ConnectionHub - 根据我的经验似乎是必要的(旧的应该由GC处理)

码:

private HubConnection _hubConnection = null;
private IHubProxy _chatHubProxy = null;

private void InitializeConnection()
{
    if (_hubConnection != null)
    {
        // Clean up previous connection
        _hubConnection.Closed -= OnDisconnected;
    }

    _hubConnection = new HubConnection("your-url");
    _hubConnection.Closed += OnDisconnected;
    _chatHubProxy = _hubConnection.CreateHubProxy("YourHub");

    ConnectWithRetry();
}

void OnDisconnected()
{
    // Small delay before retrying connection
    Thread.Sleep(5000);

    // Need to recreate connection
    InitializeConnection();
}

private void ConnectWithRetry()
{
    // If this fails, the 'Closed' event (OnDisconnected) is fired
    var t = _hubConnection.Start();

    t.ContinueWith(task =>
    {
        if (!task.IsFaulted)
        {
            // Connected => re-subscribe to groups etc.
            ...
        }
    }).Wait();
}
Run Code Online (Sandbox Code Playgroud)


Ash*_*ian 6

我刚刚在http://www.asp.net/signalr/overview/signalr-20/hubs-api/handling-connection-lifetime-events找到答案

"如何不断重新连接

在某些应用程序中,您可能希望在连接丢失并且重新连接尝试超时后自动重新建立连接.为此,您可以从Closed事件处理程序(JavaScript客户端上的已断开事件处理程序)调用Start方法.您可能希望在调用Start之前等待一段时间,以避免在服务器或物理连接不可用时过于频繁地执行此操作.以下代码示例适用于使用生成的代理的JavaScript客户端.

$.connection.hub.disconnected(function() {
   setTimeout(function() {
       $.connection.hub.start();
   }, 5000); // Restart connection after 5 seconds.
});
Run Code Online (Sandbox Code Playgroud)

移动客户端需要注意的一个潜在问题是,当服务器或物理连接不可用时,连续重新连接会导致不必要的电池耗尽."