How to re-connect to server?
Closed this issue · 8 comments
I hope my client just listens to the server, even if the server hasn’t started yet .
var WebSocket_Client = new WatsonWsClient("127.0.0.1",9000,false);
await WebSocket_Client .StartAsync();
Could u help me?
Thanks.
So nice, there are a pull request just completed it
Yes, I have it on my list to integrate that PR. In the meantime, you should create a loop around .Start
and exit the loop when the connection has been established.
So nice, there are a pull request just completed it
I started using this library and had the same problem, so I decided to use some old methods that I had using vanilla TCP Socket. Mainly waiting to receive information, connect or disconnect from the server. I have made several arrangements according to the comments of @jchristn I hope it help you. SAlu2s
Definitely on my list to integrate :) I appreciate the hard work!
Hi @flier268 I integrated @MacKey-255 's pull request. It's in NuGet v2.3.0.
Use the StartWithTimeout
or StartWithTimeoutAsync
API.
As far as automatically reconnecting, you can add logic into your code in the ServerDisconnected
event.
Commit: 1992cea
NuGet: https://www.nuget.org/packages/WatsonWebsocket/2.3.0
Thanks for @jchristn @MacKey-255, both of you are really efficient
But, a feature what i want is this.
private static Dictionary<WatsonWsClient, CancellationTokenSource> watsonWsClientsListening = new Dictionary<WatsonWsClient, CancellationTokenSource>();
/// <summary>
/// Auto re-connect to server after disconnected
/// </summary>
/// <param name="watsonWsClient"></param>
/// <param name="reconnectTime">after x ms, then reconnect</param>
public static void Listen(this WatsonWsClient watsonWsClient, int reconnectTime = 3000)
{
if (watsonWsClientsListening.ContainsKey(watsonWsClient))
return;
CancellationTokenSource cts = new CancellationTokenSource();
// Pass the token to the cancelable operation.
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
{
CancellationToken token = (CancellationToken)obj;
watsonWsClient.ServerDisconnected += async (object? sender, EventArgs e) =>
{
SpinWait.SpinUntil(() => cts.IsCancellationRequested, reconnectTime);
if (!cts.IsCancellationRequested)
await watsonWsClient.StartAsync();
};
}), cts.Token);
watsonWsClient.Start();
}
public static void UnListen(this WatsonWsClient watsonWsClient)
{
if (!watsonWsClientsListening.ContainsKey(watsonWsClient))
return;
watsonWsClientsListening[watsonWsClient].Cancel();
watsonWsClientsListening.Remove(watsonWsClient);
}
It can re-connect to server, after disconnected.
Automatic reconnect is not something I'm comfortable building into the library. If you'd like to submit a PR that follows the design pattern of the library, I'd be happy to take a look. Cheers