温馨提示×

如何在C#中实现TcpClient的自动重连

c#
小樊
89
2024-08-29 20:15:36
栏目: 编程语言

在C#中实现TcpClient的自动重连,可以通过封装一个自定义的TcpClient类,该类包含重连逻辑

using System;
using System.Net.Sockets;
using System.Threading;

public class ReconnectingTcpClient
{
    private TcpClient _tcpClient;
    private string _host;
    private int _port;
    private int _reconnectInterval; // 重连间隔(毫秒)
    private bool _isConnected;
    private Thread _reconnectThread;

    public ReconnectingTcpClient(string host, int port, int reconnectInterval = 1000)
    {
        _host = host;
        _port = port;
        _reconnectInterval = reconnectInterval;
        _tcpClient = new TcpClient();
    }

    public void Connect()
    {
        _isConnected = true;
        _reconnectThread = new Thread(Reconnect);
        _reconnectThread.Start();
    }

    private void Reconnect()
    {
        while (_isConnected)
        {
            try
            {
                if (!_tcpClient.Connected)
                {
                    _tcpClient.Connect(_host, _port);
                    Console.WriteLine("已连接到服务器");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接失败: {ex.Message}");
                Thread.Sleep(_reconnectInterval);
            }
        }
    }

    public void Disconnect()
    {
        _isConnected = false;
        _tcpClient.Close();
        Console.WriteLine("已断开与服务器的连接");
    }

    public void Send(byte[] data)
    {
        if (_tcpClient.Connected)
        {
            NetworkStream stream = _tcpClient.GetStream();
            stream.Write(data, 0, data.Length);
        }
    }

    public byte[] Receive()
    {
        if (_tcpClient.Connected)
        {
            NetworkStream stream = _tcpClient.GetStream();
            byte[] buffer = new byte[_tcpClient.ReceiveBufferSize];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);
            byte[] receivedData = new byte[bytesRead];
            Array.Copy(buffer, receivedData, bytesRead);
            return receivedData;
        }
        return null;
    }
}

使用示例:

class Program
{
    static void Main(string[] args)
    {
        ReconnectingTcpClient client = new ReconnectingTcpClient("127.0.0.1", 8000);
        client.Connect();

        // 发送和接收数据...

        client.Disconnect();
    }
}

这个示例中的ReconnectingTcpClient类包含了自动重连逻辑。当调用Connect()方法时,会启动一个新线程来处理重连。如果连接丢失,线程会尝试每隔指定的时间间隔(默认为1秒)重新连接。你可以通过修改_reconnectInterval变量来调整重连间隔。

0