20-ESP8266 SDK開發基礎入門篇--C# TCP客戶端編寫 , 加入數據通訊

http://www.javashuo.com/article/p-mjnxnecd-r.htmlhtml

 

自行調整頁面服務器

 

 

 

 

 鏈接上之後主動發個數據網絡

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

 

測試優化

 

 

 

關閉窗體的時候,關閉下TCPspa

 

 

 

 

再優化一下,,檢測服務器主動斷開線程

 

 

 

//檢測服務器是主動斷開
                    if ((myTcpClient.Client.Poll(20, SelectMode.SelectRead)) && (myTcpClient.Client.Available == 0))
                    {
                        myTcpClient.Close();//關閉之後,後面程序會引起異常
                    }

 

 

測試3d

 

 

 

 

 

 

 

 

 如今寫發送,自行雙擊那個按鈕,,,讓軟件添加上那個按鈕的點擊事件code

 

 

 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顯示  和清除 你們本身搞定哈,,,

 

 

 

http://www.javashuo.com/article/p-fnmkooai-bu.html

相關文章
相關標籤/搜索