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
Differences to phoenix's answer:
OnDisconnected
is actually required since the Closed
event is fired on connection failureCode:
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();
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With