Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting connection lost in SignalR from client side

I am connecting a simple application to a server that hosts my web-pplication. My web-application uses SignalR 2. Everything is going smooth and my little application can sync with the web-application and receives messages sent from it. But, when the web-page is updated or the server restarts and it loses its connections, the application cannot understand that the connection is lost from server. The following is my codes:

// initializing connection
HubConnection connection;
IHubProxy hub;

connection = new HubConnection(serverAddress);
hub = connection.CreateHubProxy("MyPanel");
hub.On<string>("ReciveText", (msg) => recieveFromServer(msg));

A thread checks the connection every 1 minutes, but every time it checks, the state of the connection is “Connected” while the connection from server side is lost. Is there anything that I am missing here?

if (connection.State == ConnectionState.Disconnected)
{
    // try to reconnect to server or do something
}
like image 840
LeXela-ED Avatar asked Jan 25 '26 08:01

LeXela-ED


1 Answers

You can try something like that :

Comes from signalR official examples.

connection = new HubConnection(serverAddress);    
connection.Closed += Connection_Closed;

/// <summary>
/// If the server is stopped, the connection will time out after 30 seconds 
/// the default, and the `Closed` event will fire.
/// </summary>
void Connection_Closed()
{
 //do something
}

You can use StateChanged event too like this :

connection.StateChanged += Connection_StateChanged;

private void Connection_StateChanged(StateChange obj)
{
      MessageBox.Show(obj.NewState.ToString());
}

EDIT

You can try to reconnect every 15 secs with something like that :

private void Connection_StateChanged(StateChange obj)
{

    if (obj.NewState == ConnectionState.Disconnected)
    {
        var current = DateTime.Now.TimeOfDay;
        SetTimer(current.Add(TimeSpan.FromSeconds(30)), TimeSpan.FromSeconds(10), StartCon);
    }
    else
    {
        if (_timer != null)
            _timer.Dispose();
    }
}

private async Task StartCon()
{
    await Connection.Start();
}

private Timer _timer;
private void SetTimer(TimeSpan starTime, TimeSpan every, Func<Task> action)
{
    var current = DateTime.Now;
    var timeToGo = starTime - current.TimeOfDay;
    if (timeToGo < TimeSpan.Zero)
    {
        return;
    }
    _timer = new Timer(x =>
    {
        action.Invoke();
    }, null, timeToGo, every);
}
like image 87
Quentin Roger Avatar answered Jan 28 '26 21:01

Quentin Roger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!