Team XSockets.NET

How to AutoReconnect

By default the client will not reconnect if the connection is closed, but by just calling the SetAutoReconnect() method, you can pass in a timeout for the reconnect to occur. By default the timeout is 5 seconds.

If the connection is closed and autoreconnect is enabled the client will try to reconnect, if that reconnect fails the event OnAutoReconnectFailed will be invoked. This way you can implement some custom logic between attempts to reconnect.

A simple sample where out IXSocketClient is _client, we also have a failcounter and after 4 attempts we stop trying to reconnect.

//Using the default timeout
//If the reconnect fails...
_client.OnAutoReconnectFailed += (sender, eventArgs) =>
    Console.WriteLine("AutoReconnect Failed");
    if (fail > 4)
        _client.AutoReconnect = false;


This code will just open a connection and try to reconnect every 15 second if the connection is closed. By default the reconnect timeout is set to 5 seconds interval.

var c = new XSockets.XSocketClient("ws://localhost:4502", "http://localhost", "generic");
c.OnConnected += (s, e) => { Console.WriteLine("Connected"); };
c.OnDisconnected += (s, e) => { Console.WriteLine("Disconnected"); };
c.OnAutoReconnectFailed += (s, e) => { Console.WriteLine("AutoReconnect failed"); };
var r = await c.Open();
Console.WriteLine("Open: {0}",r);


By closing the server the OnDisconnected event will be fired on the client. Then we let the server be down for more than 30 seconds. This way we will get 2 OnAutoReconnectFailed events triggered. Then when we start the server the client will AutoReconnect and the OnConnected event will fire.


results matching ""

    No results matching ""