首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在达到连接的最大重试次数时继续尝试连接到websocket?

如何在达到连接的最大重试次数时继续尝试连接到websocket?
EN

Stack Overflow用户
提问于 2018-10-25 16:51:49
回答 1查看 2.8K关注 0票数 1

我目前使用的是一个需要通过websocket连接到用C++编写的软件的C#应用程序。C#应用程序是客户端,C++软件是服务器。我希望C#应用程序在未连接的情况下每隔5秒尝试重新连接到websocket。我目前使用的是websocket-sharp。

这是我到目前为止的代码:

代码语言:javascript
复制
using System;
using System.Threading;
using WebSocketSharp;

namespace ConsoleApp1
{
    class Program
    {
         static void Main(string[] args)
         {
            using (var ws = new WebSocket("ws://192.168.1.25:50000"))
            {
                ws.OnMessage += (sender, e) =>
                {
                    Console.WriteLine("Message received : " + e.Data);
                    if (e.Data == "alreadyConnected")
                    {
                        ws.Send("forceConnect");
                    }
                    if (e.Data == "connexionEstablished")
                    {
                        ws.Send("Hello server");
                    }
                };

                ws.OnOpen += (sender, e) =>
                {
                    Console.WriteLine("Connexion has been established");
                    ws.Send("some message");
                };

                ws.OnClose += (sender, e) =>
                {
                    Console.WriteLine("Connexion has been lost");
                    if (!e.WasClean)
                    {
                        if (!ws.IsAlive)
                        {
                            Thread.Sleep(5000);
                            ws.Connect();
                        }
                    }
                };

                ws.OnError += (sender, e) =>
                {
                    Console.WriteLine("Connexion has led to an error");
                };

                ws.Connect();
                Console.ReadKey(true);
            }
        }
    }
}

但是在10次不成功的尝试之后,我得到了一条错误消息"A series of reconnecting failed“。这是由于websocket-sharp中固定的最大重试次数造成的。在我收到这条消息后,我没有找到继续尝试重新连接的方法(也没有单独尝试,也没有在互联网上搜索)。有没有人知道我能做什么?

如果有人能帮上忙,我将非常感激:)祝你愉快!

EN

回答 1

Stack Overflow用户

发布于 2019-01-03 20:46:14

下面是我使用的一些高级代码,用于在主机和客户端之间的连接由于某种原因中断时不断尝试重新连接。下面的代码片段本身并未经过测试,但我在产品代码中使用了类似的结构。

一个额外的需求是WebSocketSharp library,它包含所有的元素,使得Websocket编码非常容易。

代码语言:javascript
复制
using System;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

using WebSocketSharp;



namespace Application1
{
    class Program
    {


        static void Main(string[] args)
        {

            // Locals
            string host         = "127.0.0.1";
            int port            = 8080;
            int Frq_Reconnect   = 10000;
            WebSocket ws;

            // Start WebSocket Client
            ws              = new WebSocket(string.Format("ws://{0}:{1}", host, port));
            ws.OnOpen       += new EventHandler(ws_OnOpen);
            ws.OnMessage    += new EventHandler<MessageEventArgs>(ws_OnMessage);
            ws.OnError      += new EventHandler<ErrorEventArgs>(ws_OnError);
            ws.OnClose      += new EventHandler<CloseEventArgs>(ws_OnClose);


            // Connection loop
            while (true)
            {
                try
                {
                    if (!ws.IsAlive)
                    {
                        ws.Connect();
                        if (ws.IsAlive)
                        {
                            ws.Send(JsonConvert.SerializeObject(json, Formatting.None));
                        }
                        else
                        {
                            Console.WriteLine(string.Format("Attempting to reconnect in {0} s", Frq_Reconnect / 1000));
                        }
                    }
                }
                catch (Exception e)
                {
                    string errMsg = e.Message.ToString();
                    if (errMsg.Equals("The current state of the connection is not Open."))
                    {// remote host does not exist
                        Console.WriteLine(string.Format("Failed to connect to {0}:{1}", host, port));
                    }
                    if (errMsg.Equals("A series of reconnecting has failed."))
                    {// refusal of ws object to reconnect; create new ws-object

                        ws.Close();

                        ws             = new WebSocket(string.Format("ws://{0}:{1}", host, port));
                        ws.OnOpen     += new EventHandler(ws_OnOpen);
                        ws.OnMessage  += new EventHandler<MessageEventArgs>(ws_OnMessage);
                        ws.OnError    += new EventHandler<ErrorEventArgs>(ws_OnError);
                        ws.OnClose    += new EventHandler<CloseEventArgs>(ws_OnClose);

                    }
                    else
                    {// any other exception
                        Console.WriteLine(e.ToString());
                    }

                }


            // Callback handlers
            void ws_OnClose(object sender, CloseEventArgs e)
            {
                Console.WriteLine("Closed for: " + e.Reason);
            }

            void ws_OnError(object sender, ErrorEventArgs e)
            {
                Console.WriteLine("Errored");
            }

            void ws_OnMessage(object sender, MessageEventArgs e)
            {
                Console.WriteLine("Messaged: " + e.Data);
            }

            void ws_OnOpen(object sender, EventArgs e)
            {
                Console.WriteLine("Opened");
            }



        }// end      static void Main(...)



    }
}

这会捕获WebSocket对象超时异常,清除当前对象实例,然后创建一个新实例。随后,整个连接环路继续。

对我来说,上面的内容让我尝试整晚重新连接……

此外,此代码的结构确保在长时间的连接重试时不会出现堆栈溢出。例如,我见过有人在On_Close事件处理程序中处理连接中止。这最终是行不通的,因为这样的方法会导致重新实例化WebSocket对象,并最终导致系统资源耗尽。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52985180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档