20-ESP8266 SDK开发基础入门篇--C# TCP客户端编写 , 加入数据通信

https://www.cnblogs.com/yangfengwu/p/11192594.html

 

自行调整页面

 

 

 

 

 连接上以后主动发个数据

namespace TCPClient
{
    public partial class Form1 : Form
    {
        private TcpClient myTcpClient = null;// TcpClient

        Thread ConnectThread;//连接线程

        string ipAddress;//记录ip地址
        int Port = 0;//端口号

        private NetworkStream networkstrem = null;//获取网络数据用
        private Thread ReceiveThread;//接收消息线程
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            getIPAddress();//刚才写的那个函数.获取电脑IP,并显示在下拉框
        }


        /// <获取本机 IP 地址>
        /// 
        /// </summary>
        /// <returns></returns>
        private void getIPAddress()
        {
            IPAddress[] hostipspool = Dns.GetHostAddresses("");//获取本机所以IP
            comboBox1.Items.Clear();//清除下拉框里面的内容
            foreach (IPAddress ipa in hostipspool)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    comboBox1.Items.Add(ipa.ToString());//下拉框加入IP数据
                    comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;//显示第一个
                }
            }
        }


        private void ConnectMethod()
        {
            myTcpClient = new TcpClient();                      //实例化myTcpClient
            try
            {
                myTcpClient.Connect(ipAddress, Port);//连接服务器

                networkstrem = myTcpClient.GetStream();//获取数据流操作实例.(给的方法就是这个......)

                try
                {
                    networkstrem.Write(new byte[] { 0x31, 0x32, 0x33 }, 0,3);//发送数据,"123"
                }
                catch
                {

                }
                    
                //连接上以后往下执行
                Invoke((new Action(() => 
                {
                    button1.Text = "断开";
                })));
            }
            catch (Exception)
            {
                //异常处理函数
                Invoke((new Action(() =>
                {
                    button1.Text = "连接";
                })));
                try { myTcpClient.Close(); }catch { } //关闭连接
            }
        }


        //连接和断开按钮
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "连接")
            {
                ipAddress = comboBox1.Text.ToString();//获取IP地址
                Port = Convert.ToInt32(textBox1.Text.ToString());//获取端口号

                ConnectThread = new Thread(ConnectMethod);//创建任务
                ConnectThread.Start();//启动任务
            }
            else
            {
                try { myTcpClient.Close(); } catch { } //关闭连接
                Invoke((new Action(() =>
                {
                    button1.Text = "连接";
                })));
            }
        }

        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            getIPAddress();//刚才写的那个函数
        }
    }
}

 

 

 测试

 

 

 

 现在写接收数据,然后显示

 

 

 

 

 

        /// <接收消息线程>
        /// 
        /// </summary>
        private void ReceiveDataMethod()
        {
            int RecvCnt = 0;
            byte[] recvBytes = new byte[1024];
            while (true)
            {
                try
                {
                    RecvCnt = networkstrem.Read(recvBytes, 0, recvBytes.Length);//获取数据
                    Invoke((new Action(() =>
                    {
                        //new ASCIIEncoding().GetString(recvBytes, 0, RecvCnt)//byte转化为字符串
                        textBox2.AppendText(new ASCIIEncoding().GetString(recvBytes, 0, RecvCnt));//追加显示
                    })));
                }
                catch (Exception ex)
                {
                    //异常处理函数
                    Invoke((new Action(() =>
                    {
                        button1.Text = "连接";
                    })));
                    try { ReceiveThread.Abort(); }//销毁任务
                    catch { }
                    try { networkstrem.Dispose(); }//释放资源
                    catch { }
                    try { myTcpClient.Close(); }//关闭TCP
                    catch { }
                }
            }
        }

 

测试

 

 

 

关闭窗体的时候,关闭下TCP

 

 

 

 

再优化一下,,检测服务器主动断开

 

 

 

//检测服务器是主动断开
                    if ((myTcpClient.Client.Poll(20, SelectMode.SelectRead)) && (myTcpClient.Client.Available == 0))
                    {
                        myTcpClient.Close();//关闭以后,后面程序会引发异常
                    }

 

 

测试

 

 

 

 

 

 

 

 

 现在写发送,自行双击那个按钮,,,让软件添加上那个按钮的点击事件

 

 

 byte[] sendbyte = Encoding.Default.GetBytes(textBox3.Text.ToString());//获取发送的数据,转为byte
            if (sendbyte.Length > 0)
            {
                try { networkstrem.Write(sendbyte, 0, sendbyte.Length); }//发送数据
                catch (Exception) { MessageBox.Show("请检查连接", "提示!"); }
            }
            else
            {
                MessageBox.Show("数据不能为空", "提示!");
            }

 

 

 

 测试

 

 

 然后做个  Hex发送

        /// <字符串转16进制格式,不够自动前面补零>
        /// "0054FF"  ==>  16进制  0x00 0x54 0xFF
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private static byte[] strToToHexByte(String hexString)
        {
            int i;
            bool Flag = false;


            hexString = hexString.Replace(" ", "");//清除空格
            if ((hexString.Length % 2) != 0)
            {
                Flag = true;
            }
            if (Flag == true)
            {
                byte[] returnBytes = new byte[(hexString.Length + 1) / 2];

                try
                {
                    for (i = 0; i < (hexString.Length - 1) / 2; i++)
                    {
                        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    }
                    returnBytes[returnBytes.Length - 1] = Convert.ToByte(hexString.Substring(hexString.Length - 1, 1).PadLeft(2, '0'), 16);

                }
                catch
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = 0;
                    }
                    MessageBox.Show("超过16进制范围A-F,已初始化为0", "提示");
                }
                return returnBytes;
            }
            else
            {
                byte[] returnBytes = new byte[(hexString.Length) / 2];
                try
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    }
                }
                catch
                {
                    for (i = 0; i < returnBytes.Length; i++)
                    {
                        returnBytes[i] = 0;
                    }
                    MessageBox.Show("超过16进制范围A-F,已初始化为0", "提示");
                }
                return returnBytes;
            }
        }

 

 

 

 

 测试

好了,hex显示  和清除 大家自己搞定哈,,,

 

 

 

https://www.cnblogs.com/yangfengwu/p/11192618.html

 

posted on 2019-07-16 04:02  广源时代  阅读(2169)  评论(0编辑  收藏  举报

导航

支付宝 QQ群