亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何在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
平舆县| 黄骅市| 河西区| 福安市| 新巴尔虎左旗| 云阳县| 陆河县| 常熟市| 茂名市| 方山县| 霍城县| 长汀县| 全州县| 佛坪县| 木兰县| 民县| 永胜县| 平和县| 广汉市| 大荔县| 库车县| 德州市| 常州市| 湖州市| 临泉县| 垦利县| 乳山市| 福清市| 泽州县| 大同市| 麦盖提县| 贵阳市| 渑池县| 浮山县| 青河县| 韶山市| 犍为县| 襄垣县| 余江县| 清水县| 嫩江县|