简单的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);
        } :
相关推荐
勤不了一点26 分钟前
小白上手RPM包制作
linux·运维·服务器·软件工程
DanmF--33 分钟前
Protobuf工具
网络·unity·游戏引擎·游戏程序
盛夏绽放1 小时前
Python字符串常用内置函数详解
服务器·开发语言·python
兴达易控2 小时前
ProfibusDP主站转modbusTCP网关接DP从站网关通讯案例
网络
zizle_lin2 小时前
优雅使用Gunicorn进程管理FastAPI
服务器·fastapi·gunicorn
2501_906314323 小时前
MCP-RAG 服务器:完整设置和使用指南
运维·服务器
IP管家3 小时前
物联网设备远程管理:基于代理IP的安全固件更新通道方案
服务器·网络·物联网·网络协议·tcp/ip·安全·ip
搬码临时工3 小时前
远程连接电脑的方法?异地远程桌面连接和三方软件实现
运维·服务器·网络·物联网·电脑·远程工作
窦再兴4 小时前
来一个复古的技术FTP
linux·运维·服务器
陌路物是人非4 小时前
uniapp取消浏览自动填充
java·服务器·uni-app