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

标签 client signalr

我已阅读 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/

    相关文章:

    C++:客户端服务器通信:并非所有元素都使用套接字发送和接收

    java - 如何检查 AmazonS3Client 连接是否处于 Activity 状态

    signalr - 尝试发送 SignalR 组消息失败并出现异常

    asp.net-core - 如何在 Blazor 服务器应用程序中使用信号器从 http 客户端获取 token ?

    signalr - 带有信号器的 mvc6 的任何示例?

    java - 创建ejb项目时可以生成的 "client ejb"模块的用途是什么?

    concurrency - 如何允许更多并发客户端与 Netty 连接?

    android - 为简单的 Android 应用程序创建 Web 客户端的技术

    c# - 服务器经常丢失 Azure SignalR 连接

    c# - TypeError : chat. 发送不是函数