簡體   English   中英

C# 在 tcpclient 套接字上收到字符串的問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM