Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

client

signalr

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

like image 990
phoenix Avatar asked Jul 03 '13 01:07

phoenix


2 Answers

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();
}
like image 127
Dunc Avatar answered Nov 04 '22 07:11

Dunc


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();
    }
}
like image 33
phoenix Avatar answered Nov 04 '22 08:11

phoenix