找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 42|回复: 0

[工具类] C# Socket掉线自动重连

[复制链接] IP属地:广东省广州市
发表于 2024-6-15 17:57:26 | 显示全部楼层 |阅读模式
本帖最后由 shiy720 于 2024-6-15 18:00 编辑

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

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

  10.     private TcpClient client;

  11.     public void Start()
  12.     {
  13.         while (true)
  14.         {
  15.             if (client == null || !IsConnected(client))
  16.             {
  17.                 if (client != null)
  18.                 {
  19.                     client.Close();
  20.                 }

  21.                 TryConnect();
  22.             }

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

  26.     private void TryConnect()
  27.     {
  28.         try
  29.         {
  30.             client = new TcpClient(serverIPAddress, serverPort);
  31.             Console.WriteLine("Connected to server");
  32.         }
  33.         catch (Exception ex)
  34.         {
  35.             Console.WriteLine($"Failed to connect to server: {ex.Message}");
  36.             Thread.Sleep(reconnectInterval);
  37.         }
  38.     }

  39.     private bool IsConnected(TcpClient client)
  40.     {
  41.         try
  42.         {
  43.             var s = client.GetStream();
  44.             return s.CanRead && s.CanWrite;
  45.         }
  46.         catch
  47.         {
  48.             return false;
  49.         }
  50.     }
  51. }

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

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

在实际应用中,您可能还需要处理连接的读写操作、异常处理、连接状态监控等。希望这个简单示例可以帮助您实现网络连接掉线自动重连功能。如果您有更多的问题或需求,请随时提出
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|西兴社区 ( 蜀ICP备2022005627号 )|网站地图

GMT+8, 2024-9-8 11:37 , Processed in 0.588756 second(s), 21 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表