最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - WebsocketClient, safely reconnect after DisconnectionHappened - Stack Overflow

programmeradmin5浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0

You 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();
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论