91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何在C#中實現TcpClient的自動重連

c#
小樊
143
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
松潘县| 平泉县| 阿合奇县| 临安市| 佛学| 昌江| 保康县| 武川县| 革吉县| 门源| 慈利县| 北辰区| 乌兰县| 平江县| 崇仁县| 洪江市| 嘉黎县| 秦皇岛市| 永春县| 桂林市| 宾阳县| 南川市| 普格县| 南木林县| 巧家县| 巴南区| 桂东县| 定南县| 扶余县| 郯城县| 徐汇区| 治县。| 阿坝县| 包头市| 东兴市| 准格尔旗| 忻城县| 大洼县| 湖南省| 泸定县| 青浦区|