C# Socket客户端类封装,发送失败时重新创建Socket,设置接收数据超时

首次发布:2024-05-22 16:32

结果实体类

public class ResultModel
{
    /// <summary>
    /// 1:成功  2:失败
    /// </summary>
    public int Code { get; set; }
    public string Msg { get; set; }
}

Socket客户端类封装

public class SocketClient
{
    Socket socketClient;
    public string IP, Port;
    public SocketClient(string IP, string Port)
    {
        this.IP = IP;
        this.Port = Port;
        //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
        socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }
    /// <summary>
    /// 创建Scoket 客户端
    /// </summary>
    /// <param name="IP"></param>
    /// <param name="prot"></param>
    /// <returns></returns>
    public ResultModel CreateSocket()
    {
        ResultModel result = new ResultModel();
        try
        {
            if (socketClient != null)
            {
                socketClient.Close();
            }
            //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //发送信息 需要1个IP地址和端口号
            IPAddress ipaddress = IPAddress.Parse(IP); //获取文本框输入的IP地址
                                                       //将IP地址和端口号绑定到网络节点endpoint上 
            IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(Port)); //获取文本框上输入的端口号
                                                                              //向指定的ip和端口号的服务端发送连接请求 用的方法是Connect 不是Bind
            socketClient.Connect(endpoint);

            var v = socketClient.LocalEndPoint;

            result.Code = 1;
            result.Msg = "创建Socket连接成功";
        }
        catch (Exception ex)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $"=>{IP}," + ex.Message);
            result.Code = 2;
            result.Msg = "创建Socket连接失败";
        }
        return result;
    }

    public ResultModel Send(byte[] data)
    {
        ResultModel result = new ResultModel();
        try
        {
            if (socketClient == null || !socketClient.Connected)
            {
                CreateSocket();
            }
            socketClient.Send(data);
            result.Code = 1;
            result.Msg = $"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}=>{IP}ent.," + "发送成功";
            //Console.WriteLine(result.Msg);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}发送=>{IP}," + ex.Message);
            if (CreateSocket().Code == 1)
            {
                if (Send(data).Code == 1)
                {
                    result.Code = 1;
                    result.Msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $"IP:{this.IP},重新创建Socket连接,发送成功";
                    Console.WriteLine(result.Msg);
                }
                else
                {
                    result.Code = 2;
                    result.Msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $"IP:{this.IP},重新创建Socket连接,发送失败";
                    Console.WriteLine(result.Msg);
                }
            }
            else
            {
                result.Code = 2;
                result.Msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $"IP:{this.IP},连接断开,重新创建Socket连接失败";
                Console.WriteLine(result.Msg);
            }
        }
        return result;
    }
    /// <summary>
    /// 数据接收
    /// </summary>
    /// <param name="timeout"></param>
    /// <returns></returns>
    public byte[] Receive(int timeout)
    {
        byte[] data = new byte[] { };
        byte[] buffer = new byte[5120];//5K字节
        DateTime t = DateTime.Now;
        try
        {
            socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);//设置接收超时间 时间
            int length = socketClient.Receive(buffer);
            data = buffer.Take(length).ToArray();
            return data;
        }
        catch (Exception ex)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $"接收=>{IP},{ex.Message}");
            return data;
        }
    }
    public void Close()
    {
        try
        {
            if (socketClient != null)
            {
                if (socketClient.Connected)
                {
                    socketClient.Close();
                }
            }
        }
        catch { }
    }
}

方法调用

SocketClient client = new SocketClient("192.168.1.115", "9000");
ResultModel result = client.Send(new byte[]{0x01,0x02,0x03});//发送数据
byte[] rData = client.Receive(1000);//接收数据 超时为1秒
client.Close();//关闭Socket

本文来自 www.luofenming.com