2013-03-18 126 views
0

我創建了一個發送get server list命令的客戶端,但收到的字節不可讀。c#udp客戶端receivebtye無法讀取

這裏是我的代碼:

byte[] receiveBytes = udp.Receive(ref RemoteIpEndPoint); 

    string[] returnData = Encoding.Default.GetString(udp.Receive(ref RemoteIpEndPoint)).Split('\\'); 
    textBox1.Lines = returnData; 

在當地人,我看到寫值enter image description here

但是程序告訴我這個

enter image description here

有人可以告訴我,什麼是錯的我的代碼?

好吧,我改變我的代碼

yte[] receiveBytes = udp.Receive(ref RemoteIpEndPoint); 
    int size = receiveBytes.Length; 
    int i = 0; 
    while (i <= size-5) 
    { 

     string ip = receiveBytes[i] + "." + receiveBytes[i + 1] + "." + receiveBytes[i + 2] + "." + receiveBytes[i + 3] ; 
     int port = receiveBytes[i + 4] * 256 + receiveBytes[i + 5]; 

     textBox1.Text += ip + ":" + port.ToString() + Environment.NewLine; 
     i = i + 6; 
    } 

但收到的數據右心不是!

我在php上找到smiler代碼及其工作。

$data = explode("\\", $data); 

for($i=0, $o=0; $i<count($data); $i++) { 
    if (strlen($data[$i])>=4) { //fix 

     // First 4 bytes are the ip: 
     $list_server[$o]['ip']=ord($data[$i][0]).".".ord($data[$i][1]).".".ord($data[$i][2]).".".ord($data[$i][3]); 

     // Last 2 bytes are the port, Takes penultimate number and multiply by 256 and sum with the last number: 
     $list_server[$o]['port']=(ord($data[$i][4])*256) + ord($data[$i][5]); 
     //GetName($list_server[$o]['ip'],$list_server[$o]['port']); 
     $o++; 
    } 
} 

我不能猜測我的代碼有什麼問題。

+2

你使用哪種協議? Quake3的?你想要做什麼? – Eun 2013-03-18 15:10:11

+0

yeap是Quale3,我想要創建服務器列表和狀態 – madman 2013-03-18 15:27:11

+0

即使英語不是您的母語,您至少可以嘗試編寫適當的句子。 – jgauffin 2013-03-18 15:31:14

回答

0

您假設整個UDP數據包是英文可讀消息。這幾乎從未如此。

您需要研究您連接的服務器使用的協議。例如,它可能會向您發送它希望您返回的標識符列表,以查找該特定服務器的更多詳細信息。

編輯:

你最新的PHP版本使用\分離的地址,所以他們如下發送:

127.0.0.1:8080\192.168.0.1:9000\8.8.8.8:80 

這將被編碼爲(空間增加了清晰度):

7F000001 1F90 5C c0A80001 2328 5C 08080808 0050 

我沒有在您的示例中看到任何對\字符的引用,因此您可能會將此示例解碼爲(注意您通常會不能使用它,但你修改了你的警戒條款來隱藏這個bug):

127.0.0.1:8080 
92.192.168.0:291 
40.92.8.8:2056 
+0

我想出了問題是在字符串,它應該是一個int。現在即時通訊面臨另一個問題... – madman 2013-03-18 18:33:47

+0

@madman:你得到什麼輸出與你期待什麼?你最新的C#代碼看起來很準確。 – Guvante 2013-03-19 04:59:49

+0

問題是我的IP:端口沒有準確和錯誤。但PHP代碼給了我準確的結果,我找不到原因 – madman 2013-03-20 13:56:17