简单的TCPSocket客户端使用案例(已入OPCommon)

做一个实体操作工具类(包含)

csharp 复制代码
public delegate void TcpClientReceivedEventHandler(TcpClientStateEventArgs args);

    public  class TCPSocketClient
    { 
        //接收委托
        public event TcpClientReceivedEventHandler TcpReceived;

        private CancellationTokenSource cts = new CancellationTokenSource();
        //
        public string _ip { get; set; }
        //
        public int _port { get; set; }
        //
        Socket socket = null;
        //
        Thread thread = null;
        public bool IsConnect = false;//控制回复
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public TCPSocketClient(string ip, int port)
        {
            _ip = ip;
            _port = port;
        }
        /// <summary>
        /// 打开链接
        /// </summary>
        public void Open()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);
            socket.Connect(endPoint);
           
            thread = new Thread(Receiver);
            thread.IsBackground = true;
            thread.Start();
        }
        /// <summary>
        /// 获取数据操作
        /// </summary>
        private void Receiver()
        {
            while (!cts.IsCancellationRequested)
            {
                byte[] buffer = new byte[1024 * 1024];
                int length = socket.Receive(buffer);
                if (length > 0)
                {
                    byte[] b = new byte[length];
                    Buffer.BlockCopy(buffer, 0, b, 0, length);
                    TcpClientStateEventArgs args = new TcpClientStateEventArgs();
                    args.buffer = b;
                    TcpReceived.Invoke(args);
                }
            }
        }
        /// <summary>
        /// 发送bytes
        /// </summary>
        /// <param name="data"></param>
        public void Send(byte[] data)
        {
            if (socket!=null )
            {
                socket.Send(data);
            }
          
        }
        /// <summary>
        /// 关闭当前链接
        /// </summary>
        public void Close()
        {
            IsConnect = false;
            if (socket!=null )
            {
                socket.Close();
            } 
            thread.Abort();
            socket = null;
            thread = null;
        }
    }
    /// <summary>
    /// Tcp状态事件参数类
    /// </summary>
    public class TcpClientStateEventArgs : EventArgs
    {
        public byte[] buffer = null;
    }
 
 

然后简单的使用方法就是

csharp 复制代码
  TCPSocketClient tcpClient = null;

        /// <summary>
        /// 其他测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (BTSocket.Text.Equals("链接Socket"))
            {
                BTSocket.Text = "断开";
                string ip = TBSocketIp.Text.Trim();
                int port = int.Parse(TBPort.Text.Trim());
                tcpClient = new TCPSocketClient(ip, port);
                tcpClient.Open();
                tcpClient.TcpReceived += TcpClient_TcpReceived;
            }
            else
            {
                BTSocket.Text = "链接Socket";
                tcpClient.Close();
            }
        }
        /// <summary>
        /// 接受数据
        /// </summary>
        /// <param name="args"></param>
        private void TcpClient_TcpReceived( TcpClientStateEventArgs args)
        {
            string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + ":";
            str += Encoding.UTF8.GetString(args.buffer);
            this.Invoke(new Action(() =>
            {
                LBRemark.Text = str;
            }));
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click_1(object sender, EventArgs e)
        {
            byte[] Bytes = OPCommon.ConvertType.HexStringToByteArray(TBSend.Text);
            tcpClient.Send(Bytes);
        } :
相关推荐
LLLuckyGirl~22 分钟前
计算机网络之---MAC协议
网络·计算机网络·macos
WoTrusSSL2 小时前
SSL 证书格式和证书文件扩展名:完整指南
网络·网络协议·ssl
张声录12 小时前
【Prometheus】【Blackbox Exporter】深入解析 ProbeTCP 函数:如何实现 Go 中的 TCP/SSL 协议探测
tcp/ip·golang·prometheus
wang09072 小时前
SSL,TLS协议分析
网络·网络协议·ssl
高 朗4 小时前
【GO基础学习】项目日志zap Logger使用
服务器·学习·golang·日志·zap
鼾声鼾语4 小时前
thingsboard通过mqtt设备连接及数据交互---记录一次问题--1883端口没开,到服务器控制面板中打开安全组1883端口
运维·服务器·安全
说私域5 小时前
优质内容在个人IP运营中的重要性:以开源AI智能名片商城小程序为应用实例的深度探讨
人工智能·tcp/ip·小程序
网络安全-杰克6 小时前
开源靶场1
网络·web安全·开源
yngsqq6 小时前
寻找最短路径
运维·服务器·windows
Hacker_Nightrain6 小时前
CTF知识点总结(三)
网络·安全·web安全