中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

如何在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
泰安市| 上杭县| 宝丰县| 北流市| 镇坪县| 浠水县| 东山县| 霍城县| 永福县| 肇东市| 宁强县| 鄱阳县| 金昌市| 会东县| 定西市| 万年县| 南丹县| 汉沽区| 兴化市| 内乡县| 基隆市| 家居| 尼木县| 拜泉县| 灵寿县| 上饶县| 舟山市| 闸北区| 柳河县| 南皮县| 喀喇| 凤山市| 交城县| 易门县| 平顶山市| 德化县| 海原县| 永嘉县| 泾川县| 无为县| 江安县|