gpt4 book ai didi

client - SignalR .Net 客户端 : how to re-establish a connection

转载 作者:行者123 更新时间:2023-12-03 20:15:01 30 4
gpt4 key购买 nike

我已阅读 this post

In some applications you might want to automatically re-establish a connection after it has been lost and the attempt to reconnect has timed out. To do that, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients). You might want to wait a period of time before calling Start in order to avoid doing this too frequently when the server or the physical connection are unavailable. The following code sample is for a JavaScript client using the generated proxy.



当我从 Closed 事件调用 Start 方法时
connection.Closed += connection_Closed;
static void connection_Closed()
{
Console.WriteLine("connection closed");
ServerConnection.Start().Wait();
}

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

我希望它一直持续到服务器正常时它成功。不要抛出异常。我如何达到这一点。

有任何想法吗?

谢谢

最佳答案

与凤凰的答案的不同之处:

  • 没有明确调用 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();
    }

    关于client - SignalR .Net 客户端 : how to re-establish a connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17438428/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com