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

How to realize disconnection reconnection?

Open Naylor55 opened this issue 3 years ago • 1 comments

How to realize disconnection reconnection? We now encounter the following scenario: After the server is restarted, the client loses its connection, and they cannot continue to communicate unless the client is restarted.

Naylor55 avatar Jan 28 '23 02:01 Naylor55

When the websocket-server is restarted, the client will lose the connection with the server. If the reconnection mechanism is not introduced, the business data will not be updated in real time until the client is restarted manually. This is definitely not allowed in actual use, so the reconnection mechanism needs to be introduced. After snapping to the connection closing, try to reconnect.

The number of retries is 5, and the retry interval is 5s. The example code is as follows:


 //连接关闭
wsLabel.OnClose += (sender, e) =>
{
    OnWsLabelClose(sender, e);
};


......


int retry = 0;
/// <summary>
/// 连接关闭
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWsLabelClose(object sender, CloseEventArgs e)
{
    Log.LogInfo.Info("OnWsLabelClose,retry=" + retry);
    if (retry < 5)
    {
        retry++;
        Thread.Sleep(5000);
        wsLabel.Connect();
    }
    else
    {
        wsLabel.Log.Error("The reconnecting has failed.");
        Log.LogInfo.Info("重新连接失败,超过最大重试次数");
    }
}


        

Naylor55 avatar Jan 29 '23 02:01 Naylor55