Echlo
Echlo

Reputation: 43

How to keep trying connection to websocket even when max retry count for connection has been reached ?

I am currently using a C# application that needs to connect via websocket to a software that has been coded in C++. The C# application is the client, the C++ software the server. I would like the C# application to try reconnecting to the websocket every 5 seconds if it is not connected. I am currently using websocket-sharp.

This is my code so far :

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);
            }
        }
    }
}

But after 10 unsuccessful tries, I get an error message "A series of reconnecting have failed". This is due to a max number of retry fixed in websocket-sharp. After I get this message, I have found no way (nor trying alone neither searching on the internet) to keep on trying to reconnect. Does someone know a way I can do that ?

If someone could help, I'd be very thankful :) Have a nice day !

Upvotes: 1

Views: 6475

Answers (1)

supersausage007
supersausage007

Reputation: 93

The following is some high-level code I use to continuously attempt to reconnect should the connectivity between host and client be interrupted for some reason. The below snippet is untested by itself, but I am using similar constructs in production code.

An additional requirement is the WebSocketSharp library, which contains all elements to make Websocket coding very easy.

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(...)



    }
}

This catches the WebSocket object time-out exception, cleans the current object instance, and then creates a new one. Subsequently to overall connection loop continues.

For me, the above lets me try to re-connect all night...

Further, the structure of this code ensure there are no stack-overflows upon a long series of connection retries. For example, I have seen people handling connection aborts in the the On_Close event handler. This ultimately does not work, because such an approach results in renewed instantiation of the WebSocket object and eventually leads to depletion of system resources.

Upvotes: 2

Related Questions