2013-01-02 57 views
2

我試圖創建一個Windows應用程序與Visual Studio 2012,但奇怪的東西似乎正在發生......當我在控制檯中運行完全相同的代碼應用程序,它工作正常,但似乎我不能輸出下一次我在一個Windows應用程序項目一個線程中運行它:Encoding.ASCII.GetString返回空白值(僅在Windows應用程序中)

private void VisualUDPListener_Load(object sender, EventArgs e) 
    { 
     //System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false; 
     new Thread(delegate() 
     { 
      StartListener(); 
     }).Start(); 
    } 

    private void StartListener() 
    { 

     UdpClient listener = new UdpClient(listenPort); 
     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); 

     try 
     { 
      while (true) 
      { 
       //log text box 
       Log.AppendText("Listening \n"); 

       byte[] bytes = listener.Receive(ref groupEP); 

       string hex_string = BitConverter.ToString(bytes);//this works and returns the correct hex data 
       string ascii_string = Encoding.ASCII.GetString(bytes, 0, bytes.Length);//blank??????????? 

       MessageBox.Show(ascii_string.Length.toString());//outputs 131 which is correct 

       MessageBox.Show(ascii_string);// shows a blank message box 
       Log.AppendText("--" + ascii_string + hex_string +" \n");//only outputs -- 
      } 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 
     finally 
     { 
      listener.Close(); 
     } 
    } 

我指定的.NET Framework 4.5。如果我發送UDP數據從一個測試Java應用程序它收到的數據罰款,但如果我通過移動設備發送完全相同的數據,該代碼旨在爲它出現空如上面的評論。 (然後設備必須發送損壞的數據?因爲如果上面的代碼運行在一個控制檯應用程序它運行完美,並輸出正確的字符串)

任何幫助將不勝感激。

+4

數據是否包含任何點的0字節? –

+0

如果Encoding.ASCII.GetString工作並且不工作,hex_string的外觀如何? –

+0

爲什麼不能Encoding.ASCII.GetString(bytes); ??? – scartag

回答

3

如註釋中所述,字符串以0字節(00-04-02-00-20)開頭。 這正確得到轉換爲C#字符串。 MessageBox.Show調用windows api函數MessageBox。 Windows API使用零終止的字符串,所以這個特定的字符串對於WinAPI來說是空的,因爲第一個字節是零。您無法逐字記錄/顯示使用零終止字符串的API的字符串。

您需要用別的東西代替0,比如ascii_string.Replace((char)0, (char)1),或者使用不將零視爲特殊字符的apis。