2011-09-08 170 views
1

夥計!我寫一個簡單的程序來發送消息到遊戲服務器(反恐精英),該消息被用於查詢服務器的信息,它有一個固定的格式:java發送UDP數據包問題

0xff, 0xff, 0xff, 0xff, 0x54, 0x53, 0x6f, 0x75, 
0x72, 0x63, 0x65, 0x20, 0x45, 0x6e, 0x67, 0x69, 
0x6e, 0x65, 0x20, 0x51, 0x75, 0x65, 0x72, 0x79, 
0x00 

我的Java程序:

import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 

public class Test { 

    private static DatagramSocket ds; 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     try { 
      ds = new DatagramSocket(27022); 
      byte[] data; 
      // TSource Engine Query 
      char peer0_0[] = { 
       0xff, 0xff, 0xff, 0xff, 
       0x54, 0x53, 0x6f, 0x75, 
       0x72, 0x63, 0x65, 0x20, 
       0x45, 0x6e, 0x67, 0x69, 
       0x6e, 0x65, 0x20, 0x51, 
       0x75, 0x65, 0x72, 0x79, 0x00 
      }; 
      data = new String(peer0_0).getBytes(); 

      System.out.println("send: " + new String(data)); 

      DatagramPacket dp = new DatagramPacket(data, 0, data.length, InetAddress.getByName("219.133.59.20"), 27021); 

      ds.send(dp); 
      byte[] rec = new byte[1024]; 
      DatagramPacket dp2 = new DatagramPacket(rec, 1024); 
      ds.receive(dp2); 

      System.out.println("receive: " + new String(rec)); 

      ds.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      if(ds != null) ds.close(); 
     } 
    } 

} 

但是當我運行它,我使用Wireshark捕捉包,我得到這個:

enter image description here 前四個字節0​​x3F的不是0xFF的,所以有什麼問題呢?我在Windows 7中文版上運行java 6。

回答

4

通過Stringchar[]byte[]的轉換不保證是無損的,因爲它涉及字符集轉換。

嘗試聲明peer0_0[]作爲byte數組並直接使用它。

+0

謝謝aix!但是我怎樣才能在字節中表示0xff,0xff = 255,但是java中的最大字節是127 – CaiNiaoCoder

+0

@YAMaiDie:'(byte)0xff' – NPE

+0

+1:字符和字節在Java中是兩個非常不同的東西。 –