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

发布于:2024-11-29 ⋅ 阅读:(22) ⋅ 点赞:(0)

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

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;
    }
 
 

然后简单的使用方法就是

  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);
        }