2

我正在尝试使用 Visual Studio 2012 创建一个 Windows 应用程序,但似乎正在发生奇怪的事情......当我在控制台应用程序中运行完全相同的代码时,它工作正常,但似乎我无法输出以下内容一次我在 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 ...多于。(那么设备必须发送损坏的数据?不,因为如果上面的代码在控制台应用程序中运行,它会完美运行并输出正确的字符串)

任何帮助将不胜感激。

4

1 回答 1

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)或使用不将零视为特殊字符的 api。

于 2013-01-02T23:03:03.023 回答