shiy720 发表于 2024-6-15 17:57:26

C# Socket掉线自动重连

本帖最后由 shiy720 于 2024-6-15 18:00 编辑

实现 C# 中的网络连接掉线自动重连通常涉及两方面的问题: 检测连接是否丢失和重新建立连接。下面是一个简单的示例,演示了如何实现简单的网络连接掉线自动重连机制:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class AutoReconnectClient
{
    private const string serverIPAddress = "127.0.0.1";
    private const int serverPort = 8888;
    private const int reconnectInterval = 5000; // 5 seconds

    private TcpClient client;

    public void Start()
    {
      while (true)
      {
            if (client == null || !IsConnected(client))
            {
                if (client != null)
                {
                  client.Close();
                }

                TryConnect();
            }

            Thread.Sleep(1000); // check connection every 1 second
      }
    }

    private void TryConnect()
    {
      try
      {
            client = new TcpClient(serverIPAddress, serverPort);
            Console.WriteLine("Connected to server");
      }
      catch (Exception ex)
      {
            Console.WriteLine($"Failed to connect to server: {ex.Message}");
            Thread.Sleep(reconnectInterval);
      }
    }

    private bool IsConnected(TcpClient client)
    {
      try
      {
            var s = client.GetStream();
            return s.CanRead && s.CanWrite;
      }
      catch
      {
            return false;
      }
    }
}

class Program
{
    public static void Main()
    {
      AutoReconnectClient reconnectClient = new AutoReconnectClient();
      reconnectClient.Start();
    }
}在上面的示例中,AutoReconnectClient 类负责检测连接是否丢失并重新建立连接。它持续检查连接状态并在连接丢失时尝试重新连接到服务器。可以根据实际需求调整重连的时间间隔和服务器连接信息。

需要注意的是,上述示例只展示了一个简单的自动重连机制。对于更复杂的应用程序,可能需要考虑更多的因素,例如重连次数、指数退避策略、连接失败后的处理等。

在实际应用中,您可能还需要处理连接的读写操作、异常处理、连接状态监控等。希望这个简单示例可以帮助您实现网络连接掉线自动重连功能。如果您有更多的问题或需求,请随时提出
页: [1]
查看完整版本: C# Socket掉线自动重连