[英]C# problem with string received on tcpclient socket
我有 tcp 客户端 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#v.P.@t....MT15..
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”这不是消息框的问题,我无法存储和读取数据表或 debug.write。
听起来您的数据中有一些空字符,某些API(尤其是:核心 Windows API,如MessageBox
)将视为 C 样式终止的字符串。 令人困惑的是,并非所有 API都会这样做——尤其是在托管代码中,其中的字符串不应该以空值结尾。
举个例子:
MessageBox.Show("hello\0world");
只在消息框中显示hello
:
当看到 null 字符时,可能应该问一个基本问题,即这些数据是否真的是文本的? 如果您对此感到满意,那么您可能可以将它们剥离:
string s = ... // might contain null characters
s = s.Replace("\0",""); // now it doesn't
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.