网络断开时WebSocket重新连接问题

时间:2016-12-21 06:35:36

标签: c# sockets

我正在使用以下套接字函数从套接字服务器接收数据,当我断开网络连接时,再次重新连接套接字应用程序停止接收数据。我还尝试添加一个计时器,每隔20秒检查一次套接字的状态,但它不起作用。有什么建议吗?

private WebSocket client;  //before form_load

private void Form1_Load(object sender, EventArgs e)
{
    client = new WebSocket(host);

    client.OnOpen += (ss, ee) =>
      {
         MessageBox.Show(string.Format("Connected to {0} successfully ", host));
      };

    client.OnError += (ss, ee) =>
      {
         MessageBox.Show("     Error: " + ee.Message);
      };

    client.OnMessage += (ss, ee) =>
      {
         MessageBox.Show("Message: " + ee.Message);
      };

    client.OnClose += (ss, ee) =>
      {
        MessageBox.Show(string.Format("Disconnected with {0}", host));   
    };

    client.Connect();
}

private void timer1_Tick(object sender, EventArgs e)
 {
    if(client.ReadyState.ToString()=="Closed")
       {
          client.Close();
          client = new WebSocket(host);
          client.Connect();
       }

 }

1 个答案:

答案 0 :(得分:1)

您没有提及您使用的网络套接字库/包。这是一个使用WebSocket4Net的简单工作重新连接示例。

由于AutoSendPing,它会在网络出现问题时关闭连接,如果套接字关闭,计时器会尝试重新连接。

private WebSocket client;

private void Form1_Load(object sender, EventArgs e)
{
    client = new WebSocket(host)
    {
        EnableAutoSendPing = true,
        AutoSendPingInterval = 10,
    };

    client.Opened += (ss, ee) =>
    {
        System.Diagnostics.Debug.WriteLine("Connected");
    };

    client.Error += (ss, ee) =>
    {
        System.Diagnostics.Debug.WriteLine($"Error {ee.Exception}");
    };

    client.MessageReceived += (ss, ee) =>
    {
        System.Diagnostics.Debug.WriteLine($"Message: {ee.Message}");
    };

    client.Closed += (ss, ee) =>
    {
        System.Diagnostics.Debug.WriteLine("Disconnected");
    };

    client.Open();
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (client.State == WebSocketState.Closed)
    {
        client.Open();
        System.Diagnostics.Debug.WriteLine("Trying to reconnect by timer");
    }
}