2016-06-25 30 views
1

我正在用Java编写一个服务器。这里是我的主线程代码:Java Packets mess

public class EntryThread extends Thread { 

    volatile byte[] toSend; 

    public EntryThread() { 

    } 

    public void TreatRequest(byte[] data, InetAddress IPAddress) 
    { 
     try { 
      switch (data[0]) 
      { 
       case 0: // ping 
        toSend = new byte[] { (byte) 255, data[1], (byte) 255}; 
        Server.serverSocket.send(new DatagramPacket(toSend, 3, IPAddress, 17550)); 
        break; 
       case 2: 
        break; 
      } 
     } catch (Exception e) 
     { 
      System.out.println("Exception because of a packet malformation issue. You can ignore it."); 
      e.printStackTrace(); 
     } 
    } 

    public void run() { 
     Runtime.getRuntime().addShutdownHook(new Thread(){public void run(){ 
      try { 
       Server.serverSocket.close(); 
       System.out.println("The server is shut down!"); 
      } catch (Exception e) { /* failed */ } 
     }}); 

     try { 
      Server.serverSocket = new DatagramSocket(Configuration.port); 

      byte[] receiveData = new byte[512]; 

      DatagramPacket receivePacket = new DatagramPacket(receiveData, 
           receiveData.length); 
      while(true) { 
       Server.serverSocket.receive(receivePacket); 
       byte[] data = receivePacket.getData(); 
       System.out.println("RECEIVED: " + new String(data)); 
       InetAddress IPAddress = receivePacket.getAddress(); 

       /* 
       * data[0] : command/255 if 
       * data[1] : C-ID. 
       * data[2] : arguments/content 
       */ 

       TreatRequest(data, IPAddress); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

一切似乎不错,但是当我发送数据包的一些软件(PacketSender),它开始变得怪异。这里是我的控制台:

RECEIVED: [][][][][][]... // I sent 00 in hex, no problem there) 
RECEIVED: ÿ[]ÿ[][][][]... // here's the response of the server) 
RECEIVED: [][]ÿ[][][][]... // this ÿ is still there even if I just sent 00 in hex. 

所以它只覆盖阵列上,我不得不让它变大。

所以我想知道:

  • 我怎样才能使分组数据被重置为0手每次?
  • 我可以只是得到一个包的大小的数组,而不是这个奇怪的“传递数组作为参数”的方法?
+0

在您的控制台上市,目前还不清楚是实际的输出,什么是你的评析输出。请重新格式化,将两者分开。 –

回答

0

每次收到数据包时,DatagramPacket所使用的缓冲区都不会被清除。但是,方法getLength()会告诉您在当前数据包中接收了多少数据,并且您应该使用它来限制从缓冲区中提取的内容。对于示例:

System.out.println("RECEIVED: " + new String(data,0,receivePacket.getLength())); 
+0

如果长度是1,我应该对getLength做-1? – PearlSek

+0

不,如果长度为1,则使用1.读取'String(byte [] buffer,int offset,int length)'构造函数的定义。 –

0

receive Javadoc中记载:

数据报包对象的长度字段包含的 所接收的消息的长度。

System.out.println("RECEIVED: " + new String(data, 0, receivePacket.getLength()));

相关问题