2013-03-18 53 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