PearlSek PearlSek - 11 months ago 42
Java Question

Java Packets mess

I am programming a server in Java. Here's my main thread code :

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));
case 2:
} catch (Exception e)
System.out.println("Exception because of a packet malformation issue. You can ignore it.");

public void run() {
Runtime.getRuntime().addShutdownHook(new Thread(){public void run(){
try {
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,
while(true) {
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) {

All seems good, but when I send packets with some software (PacketSender), it's starting to become weird. Here's my console :

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.

So it only overwrites on a array I'm forced to make it big.

So I would like to know :

  • How can I make the packet date to be reset to lots of 0s each time ?

  • Can I just get an array of the size of the packet, instead of this weird "pass the array as an argument" method ?


The buffer used by DatagramPacket is not cleared each time a packet is received. However, the method getLength() tells you how much data was received in the current packet, and you should be using that to limit what you extract from the buffer. For your example:

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