SignalR .Net Client: how to re-establish a connect

2020-05-19 07:31发布

问题:

I have read 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.

When I call the Start method from the Closed event

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

Exception happened: the connection has not been established.

I want it continues until it success when the server is ok. Don't throw exception. How do I reach this.

any ideas?

thanks

回答1:

on .net client, you can call start method from closed event handler. if the server is unavailable, you should make a recursive call.

e.g.

_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();
    }
}


回答2:

Differences to phoenix's answer:

  • No explicit call to OnDisconnected is actually required since the Closed event is fired on connection failure
  • Small delay before retry
  • Recreate ConnectionHub each time - seems necessary in my experience (old one should get disposed by GC)

Code:

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();
}


回答3:

I've just found an answer at http://www.asp.net/signalr/overview/signalr-20/hubs-api/handling-connection-lifetime-events

"How to continuously reconnect

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.

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

A potential problem to be aware of in mobile clients is that continuous reconnection attempts when the server or physical connection isn't available could cause unnecessary battery drain."