基於多串列埠ETH005裝置的Socket網路程式設計

暖楓無敵發表於2013-12-20

利用多串列埠裝置進行Socket網路程式設計

1、安裝多串列埠伺服器ETH005軟體。軟體下載地址:http://download.csdn.net/detail/taomanman/6762173

2、開啟ETH005軟體,點選“掃描”,如下圖:

3、會搜尋到裝置的IP地址,修改串列埠COM1的串列埠波特率為9600,通訊方式修改為485通訊,遠端IP修改成192.168.0.2,然後點選“連線”,如下圖:

4、連線完成後,點選“配置”,如下圖:

5、點選“讀取配置資訊”,如下圖:

 

6、開啟串列埠除錯助手,配置遠端主機和遠端埠號資訊,然後連線網路,然後輸入十六進位制數,然後傳送,接收區會將結果輸出,如下圖:

 

 

開始程式設計:使用Socket進行網路程式設計,傳送指令,獲取資料

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1、             建立Socket連線

Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ie = new IPEndPoint(IPAddress.Parse("192.168.0.18"), 50001);
try
{
     newclient.Connect(ie);
}
 catch (SocketException e)
{

     MessageBox.Show("連線伺服器失敗:" + e.Message);
     return;
}
ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
myThread = new Thread(myThreaddelegate);
myThread.Start();

 

2、             傳送指令

///<summary>
///傳送溫溼度資料
///</summary>
public void SendWSD()
{
    string wsd = "01 03 00 00 00 03 05 cb";
    int m_length = wsd.Length;
    byte[] data = new byte[m_length];
    //十六進位制字串轉換成字元陣列(01 03 00 00 00 03 05 cb)
    data = ConvertHelper.strToToHexByte(wsd);
    int i = newclient.Send(data, data.Length, 0);
    //showMsg("溫溼度傳送訊息為:" + wsd + "\r\n");
}

 
public static class ConvertHelper
{

    ///<summary>   
    /// 16進位制字串轉位元組陣列   
    ///</summary>   
   ///<param name="hexString"></param>   
   ///<returns></returns>   
    public static byte[] strToToHexByte(string hexString)
    {

        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
           hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
        return returnBytes;
   }

 
    ///<summary>   
    ///位元組陣列轉16進位制字串   
     ///</summary>   
    ///<param name="bytes"></param>   
    ///<returns></returns>   
     public static string byteToHexStr(byte[] bytes)
     {

        string returnStr = "";
        if (bytes != null)
        {
             for (int i = 0; i < bytes.Length; i++)
             {
                 returnStr += bytes[i].ToString("X2");
             }
        }
        return returnStr;
    }

 

    ///<summary>
    ///十六進位制轉十進位制
    ///</summary>
   ///<param name="hex"></param>
   ///<returns></returns>
    public static string Hex2Ten(string hex)
    {
        int ten = 0;
        for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
        {
            ten += HexChar2Value(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
            j--;
        }
        return ten.ToString();
    }
}

3、             接收資料

  ///<summary>
  ///接收訊息
  ///</summary>
  public void ReceiveMsg()
  {
    while (true)
    {
        byte[] data = new byte[1024];
        int recv = newclient.Receive(data);
        string stringdata = Encoding.UTF8.GetString(data, 0, recv);
        //將所讀取的字串轉換為位元組陣列
        byte[] content = Encoding.ASCII.GetBytes(stringdata);
        if (recv <= 0)
               break;
        string hexString = ConvertHelper.byteToHexStr(content);
        string sd = hexString.Substring(6, 4);
        string wd = hexString.Substring(10, 4);
       //showMsg("溫溼度接收到的返回值串為:" + hexString + "\r\n");
        //處理後的溫溼度數值
        double csd = double.Parse(ConvertHelper.Hex2Ten(sd)) / 100;
        double cwd = (double.Parse(ConvertHelper.Hex2Ten(wd)) - 27315) / 100;
        showMsg("溼度值為:" + csd + "% 採集時間:[" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "]\r\n");
        showMsg("溫度值為:" + cwd + "℃ 採集時間:[" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "]\r\n");
     }
  }

 

    ///<summary>
    ///顯示訊息
    ///</summary>
   ///<param name="msg"></param>
   public void showMsg(string msg)
   {
      {
          //線上程裡以安全方式呼叫控制元件
           if (receiveMsg.InvokeRequired)
           {
                MyInvoke _myinvoke = new MyInvoke(showMsg);
                receiveMsg.Invoke(_myinvoke, new object[] { msg });
            }
            else
            {
                receiveMsg.AppendText(msg);
            }
       }
  }
 


 

相關文章