If WebsocketClient gets a DisconnectionHappened because server went down or server wasn't running, how can I attempt another connection? I tried doing a Stop() then Reconnect() in the DisconnectionHappened but this causes a stack overflow due to recursion.
I'm not asking about the auto reconnect handler performed in ReconnectionHappened.
If WebsocketClient gets a DisconnectionHappened because server went down or server wasn't running, how can I attempt another connection? I tried doing a Stop() then Reconnect() in the DisconnectionHappened but this causes a stack overflow due to recursion.
I'm not asking about the auto reconnect handler performed in ReconnectionHappened.
Share Improve this question edited Mar 25 at 5:52 Qiang Fu 9,3871 gold badge6 silver badges16 bronze badges asked Mar 23 at 18:15 da66enda66en 3051 silver badge11 bronze badges 1- You need to close the existing connection. See mcguirev10/2019/08/17/how-to-close-websocket-correctly.html – jdweng Commented Mar 23 at 21:24
1 Answer
Reset to default 0You could try dispose instead of stop.
using Websocket.Client;
class Program
{
static async Task Main(string[] args)
{
await StartWebSocket();
Console.ReadKey();
}
public static async Task StartWebSocket()
{
var url = new Uri("ws://localhost:8080/ws");
var socketClient = new WebsocketClient(url);
socketClient.IsReconnectionEnabled = false;
socketClient.MessageReceived.Subscribe(msg => Console.WriteLine($"Received: {msg.Text}"));
socketClient.DisconnectionHappened.Subscribe(async info =>
{
socketClient.Dispose();
});
try
{
await socketClient.Start();
}
catch (Exception ex)
{
Console.WriteLine($"WebSocket connection failed and disposed, create new connection");
await StartWebSocket();
}
}
}