如何在C#中實(shí)現(xiàn)TcpClient的自動(dòng)重連

c#
小樊
133
2024-08-29 20:15:36

在C#中實(shí)現(xiàn)TcpClient的自動(dòng)重連,可以通過(guò)封裝一個(gè)自定義的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("已連接到服務(wù)器");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"連接失敗: {ex.Message}");
                Thread.Sleep(_reconnectInterval);
            }
        }
    }

    public void Disconnect()
    {
        _isConnected = false;
        _tcpClient.Close();
        Console.WriteLine("已斷開(kāi)與服務(wù)器的連接");
    }

    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();

        // 發(fā)送和接收數(shù)據(jù)...

        client.Disconnect();
    }
}

這個(gè)示例中的ReconnectingTcpClient類包含了自動(dòng)重連邏輯。當(dāng)調(diào)用Connect()方法時(shí),會(huì)啟動(dòng)一個(gè)新線程來(lái)處理重連。如果連接丟失,線程會(huì)嘗試每隔指定的時(shí)間間隔(默認(rèn)為1秒)重新連接。你可以通過(guò)修改_reconnectInterval變量來(lái)調(diào)整重連間隔。

0