[tcpclient套接字上收到字符串的C#问题

问题描述 投票:0回答:1

我有tcp clinet C#代码。它适用于连接到任何端口并获取数据。它也可以与linux / unix服务器一起工作。但是在一种情况下,当我连接到linux服务器(openwrt)时,我可以接收数据,但无法显示字符串。代码显示该字符串包含我想要的内容,但MessageBox.Show不显示该字符串。有什么问题吗?

        string ip = "192.168.0.1";
        string command ="MT15";
        string result = "None";
        int i = 0;
        int bytesRead;
        byte[] rec_message = new byte[65535];
        StringBuilder Whole_Message = new StringBuilder();
        int port = 8889;

            var client = new TcpClient();
            NetworkStream ns;
            int total = 0;

            if (!client.ConnectAsync(ip, port).Wait(1000)) { result = "Failed"; }

                    byte[] byteTime = Encoding.ASCII.GetBytes(command);
                    ns = client.GetStream();
                    ns.Write(byteTime, 0, byteTime.Length);

                    // the string.contain Shows the string contains the mac address

                    while (!result.Contains("C2:04:28:00:5F:F1"))
                    {
                        bytesRead = ns.Read(rec_message, 0, rec_message.Length);


                        total = total + bytesRead;
                        result = Encoding.ASCII.GetString(rec_message, 0, total);
                        Whole_Message.AppendFormat("{0}", result);

                        //row = Whole_Message.ToString().Split(',');


                    }
                    string r = Whole_Message.ToString();
                    // the string.contain returns true, so the string contains the mac address

                    if (r.Contains("C2:04:28:00:5F:F1"))
                    {

                        MessageBox.Show(r);
                    }
                    client.Close();

//但MessageBox仅显示“ MT15”

tcpdump数据包嗅探结果:

18:06:21.430073 IP 192.168.0.2.6481 > 192.168.0.1.8889: tcp 4
E..,HX....cg%...%....Q".....5#[email protected]..

18:06:21.439163 IP 192.168.0.1.8889 > 192.168.0.2.6481: tcp 0
E..(*.@.=..,%...%..."..Q5#v.....P....|..

18:06:21.475525 IP 192.168.0.1.8889 > 192.168.0.2.6481: tcp 23
E..?*.@.=...%...%..."..Q5#v.....P.......MT15..C2:04:28:00:5F:F1

该消息为“ MT15..C2:04:28:00:5F:F1”,但消息框中仅显示“ MT15”这不是messagebox的问题,我无法存储和读取到datatable或debug.write。

c# string visual-studio sockets tcpclient
1个回答
1
投票

声音就像您的数据中包含一些空字符,其中some API(特别是:核心Windows API,例如MessageBox)将被视为C样式终止的字符串。令人困惑的是,并非所有API都会这样做-尤其是在托管代码中,其中字符串不应以null终止。

例如:

MessageBox.Show("hello\0world");

仅在消息框中显示hello

enter image description here

[当看到空字符时,可能应该问一个基本问题,即此数据是否真的是文本的;如果您对此感到满意,则可以将它们剥离:

string s = ... // might contain null characters
s = s.Replace("\0",""); // now it doesn't
© www.soinside.com 2019 - 2024. All rights reserved.