简单的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);
        } :
相关推荐
三思而后行,慎承诺1 小时前
tcp 和http 网络知识
网络·tcp/ip·http
JavaEdge.1 小时前
LangChain4j HTTP 客户端定制:解锁 LLM API 交互的更多可能性
网络·网络协议·http
Hy行者勇哥1 小时前
形象解释 HTTP 的四种常见请求方式及其中的区别联系
网络·网络协议·http
Cuit小唐1 小时前
TCP 协议:原理、机制与应用
网络·网络协议·tcp/ip
电鱼智能的电小鱼2 小时前
EFISH-SBC-RK3588无人机地面基准站项目
linux·网络·嵌入式硬件·机器人·无人机·边缘计算
电鱼智能的电小鱼2 小时前
基于 EFISH-SBC-RK3588 的无人机环境感知与数据采集方案
linux·网络·嵌入式硬件·数码相机·无人机·边缘计算
Arenaschi3 小时前
SQLite 是什么?
开发语言·网络·python·网络协议·tcp/ip
keep intensify3 小时前
Linux常用指令
linux·服务器·php
沧浪之水!4 小时前
【Linux网络】:套接字之UDP
linux·网络·udp
BranH4 小时前
Linux系统中命令设定临时IP
linux·运维·服务器