websocket-sharp icon indicating copy to clipboard operation
websocket-sharp copied to clipboard

How to correctly check connection alive and try to reconnect every time if connection is lost in any way.

Open maciekfreak opened this issue 10 years ago • 10 comments

My script connect with the websocket server and receive data. I want to keep this connection alive forever and try to reconnect every time if server is restarting or client lost connection etc.

My script looks like below. It works fine but every time if connection is lost it freeze main thread for few seconds.

Is this a correct and best way to do this?

using UnityEngine;
using System;
using System.Collections;
using WebSocketSharp;
using WebSocketSharp.Net;

public class TestConnection  :  MonoBehaviour  {


    private WebSocket ws;
    private IEnumerator checkConnectionAlive;


    void  Start(){
        checkConnectionAlive = CheckConnectionAlive ();
        Connect ();
    }


    IEnumerator CheckConnectionAlive()
    {
        while (true) {
            Debug.Log ("checking connection");
            if (ws.IsAlive == true) {
                Debug.Log ("connected");
            } else {
                Debug.Log ("not connected");
                Disconnect ();
                Connect ();

            }

            yield return new WaitForSeconds(5);
        }
    }

    void  OnApplicationQuit()  { 
        Disconnect(); 
        StopCoroutine (checkConnectionAlive);
    }

    void  Connect()  {

        ws = new WebSocket ("ws://192.168.4.1:80");

        ws.OnOpen +=  ( sender,  e )  =>  { 
            Debug.Log  ( "WebSocket Open" ); 
        };
        ws.EmitOnPing = true;
        ws.OnMessage +=  ( sender ,  e )  =>  { 

            // handling data here

        };

        ws.OnError +=  ( sender ,  e )  =>  { 
            Debug.Log  ( "WebSocket Error Message:"  +  e.Message ); 
        };

        ws.OnClose +=  ( sender ,  e )  =>  { 
            Debug.Log  ( "WebSocket Close" + e.Reason + " --- " + e.Code ); 

        };

        ConnectF ();


    }
    private void ConnectF() {
        ws.ConnectAsync ();
        StartCoroutine(checkConnectionAlive);
    }

    void Disconnect()  { 
        ws.Close  (); 
        ws = null ; 
    }

    void Send(string message)  { 
        ws.Send(message); 
    }


} 

maciekfreak avatar Feb 25 '16 08:02 maciekfreak

Hello there,

Does your code mean that the OnClose event doesn't fire when something network failure has occurred in your environment?

And, where does your websocket-sharp come from?

sta avatar Feb 29 '16 06:02 sta

I think that OnClose is fired but sometimes even after few minutes after lost connection with server. And in this time from lost connection to onClose event main thread stop responding. I need to know that connection is lost immediately.

My code come from this github repo.

maciekfreak avatar Feb 29 '16 07:02 maciekfreak

I raised the same issue here:

https://github.com/sta/websocket-sharp/issues/228

In my case, it happens when my ISP drops my broadband connection, which lately has been happening about once a day to once every two days. It seems that connection drop's at the O/S level (i.e. the actual Internet connection and not the closing of a socket by a remote host), it really gives the websocket-sharp library a bad headache. If I try to call Disconnect() when this happens I get a variety of socket errors and have to restart the app to bring things back alive.

roschler avatar Mar 09 '16 04:03 roschler

Hey, I know this topic is a bit old, but this is the way I've been doing it -

   _ws.OnClose += WsOnOnClose;



    private void WsOnOnClose(object sender, CloseEventArgs closeEventArgs)
    {
        if (!closeEventArgs.WasClean)
        {
            if (!_ws.IsAlive)
            {
                Thread.Sleep(10000);
                _ws.Connect();
            }
        }
    }

I think this would be the best way as the connection dropping is the only time the WasClean would be false.

Bitz avatar Mar 31 '18 16:03 Bitz

@Bitz how necessary is Thread.Sleep(10000) here? Can't you do it without Sleep?

Zure1 avatar May 24 '18 11:05 Zure1

@Zure1, Yes, but do I suggest leaving it in as it will keep retrying constantly- which may be a bit unhealthy for your application, also, the 10 seconds sleep gives the environment some time to change (may it be reconnect to WiFi, change networks, what have you) ,

Bitz avatar May 24 '18 16:05 Bitz

I have the same question, my WebSocketSharp instance (client side) couldn’t filre OnClose event when my network is broken.

I checked the source codes, and it looks like the OnClose event in client side is only fired under Close method.

So my question is do we expect OnClose event is fired when the network disconnect? Or I need to implement my own websocket monitor to monitor the latest ping message, if the websocket client doesn’t receive the ping message for a while, then it should consider as disconnected.

eynzhang avatar Jan 16 '20 09:01 eynzhang

@eynzhang We have the same issue. What was your approach?

mjuchli avatar Sep 02 '20 10:09 mjuchli

@mjuchli i have same trouble, how to fix it?

ilsnk avatar Jun 29 '22 21:06 ilsnk

@ilsnk I'm afraid I can't remember and unfortunately do not have access to the project I was working on back then anymore.

mjuchli avatar Jun 29 '22 22:06 mjuchli