温馨提示×

如何在C#中实现Socket的断线重连

c#
小樊
121
2024-09-04 06:50:29
栏目: 编程语言

在C#中实现Socket的断线重连,可以通过封装一个自定义的Socket类,该类包含重连逻辑和异常处理。以下是一个简单的示例:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class ReconnectingSocket
{
    private Socket _socket;
    private EndPoint _remoteEndPoint;
    private int _reconnectInterval; // 重连间隔(毫秒)
    private bool _isConnected;
    private readonly object _lock = new object();

    public ReconnectingSocket(EndPoint remoteEndPoint, int reconnectInterval = 5000)
    {
        _remoteEndPoint = remoteEndPoint;
        _reconnectInterval = reconnectInterval;
    }

    public void Connect()
    {
        lock (_lock)
        {
            if (_isConnected) return;

            _socket = new Socket(_remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            while (!_isConnected)
            {
                try
                {
                    _socket.Connect(_remoteEndPoint);
                    _isConnected = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"连接失败: {ex.Message}");
                    Thread.Sleep(_reconnectInterval);
                }
            }
        }
    }

    public void Disconnect()
    {
        lock (_lock)
        {
            if (!_isConnected) return;

            _socket.Shutdown(SocketShutdown.Both);
            _socket.Close();
            _isConnected = false;
        }
    }

    public void Send(byte[] data)
    {
        if (!_isConnected) throw new InvalidOperationException("套接字未连接");

        try
        {
            _socket.Send(data);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发送数据失败: {ex.Message}");
            _isConnected = false;
            Connect();
        }
    }

    public byte[] Receive(int bufferSize)
    {
        if (!_isConnected) throw new InvalidOperationException("套接字未连接");

        byte[] buffer = new byte[bufferSize];

        try
        {
            int receivedBytes = _socket.Receive(buffer);
            if (receivedBytes > 0)
            {
                byte[] data = new byte[receivedBytes];
                Array.Copy(buffer, 0, data, 0, receivedBytes);
                return data;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"接收数据失败: {ex.Message}");
            _isConnected = false;
            Connect();
        }

        return null;
    }
}

使用示例:

class Program
{
    static void Main(string[] args)
    {
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 8080;
        IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);

        ReconnectingSocket socket = new ReconnectingSocket(remoteEndPoint);

        socket.Connect();

        // 发送和接收数据...

        socket.Disconnect();
    }
}

这个示例中的ReconnectingSocket类封装了一个标准的Socket对象,并在发送和接收数据时添加了重连逻辑。当连接断开时,它会尝试每隔指定的时间间隔(默认为5秒)重新连接。你可以根据需要调整重连间隔和其他参数。

0