在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
變量來調整重連間隔。