Java UDP packet size

Zbarcea Christian picture Zbarcea Christian · Feb 4, 2013 · Viewed 9.4k times · Source

In Java a single char is 16 bit, 2 bytes. That means if I want to send an UDP packet to a server, I must find the length of the string (for example) and multiply by 2?

String string = "My awesome string!";
byte[] buff = new byte[ string.length*2 ];
buff = string.getBytes();
...
packet = new DatagramPacket(buff, buff.length, address, port);
socket.send(packet);

What about the UDP packet limit? 65k a packet. For example, if I want to send data files to a server I must send 65/2k data! I'm dividing 65 into 2, and what would be the buff limit? 65/2 or 65 kb?

For example:

byte[] buff = new byte[ 65000 ]

//file and bufferreader handle
while( ( line = bufferedReader.readLine() ) != null ){
   buff = line.getBytes();
   packet = new DatagramPacket(buff, buff.length, address, port);
   socket.send(packet);
}

I have read somewhere that I can send over than 65k data, because IPv4 protocol automatically divides the packet into pieces than the receiver will merge them. Is this true?

Why I'm getting white space into my buffer? I have written a client and a server app, and I'm using a 250 size buffer. If I'm sending a word, for example "Test", which is 8 bytes long I'm getting a very long white space after the "Test" word:

byte[] buff = new byte[250];
packet = new DatagramPacket(buff, buff.length);
socket.receive(packet);
System.out.println("GET: " + buff);

and the console says:

GET: Test...........................................................................

(dots represents white space)

Answer

Andreas Fester picture Andreas Fester · Feb 4, 2013

That means if I want to send an UDP packet to a server, I must find the length of the string (for example) and multiply by 2?

No. String.getBytes() already allocates a proper array of the right length:

byte[] buff = string.getBytes();

Then, buff.length contains the proper length. Note that the length depends on the character set which was used to convert the String into the byte array.

On a side note, you should avoid using the parameter-less String.getBytes() since it uses your platform's default character set to convert the String into the byte array. Better pass the encoding explicitly:

byte[] buff = null;
try {
   buff = string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
   e.printStackTrace();
}

I have read somewhere that I can send over than 65k data, because IPv4 protocol automatically divides the packet into pieces than the receiver will merge them. Is this true?

It is true for TCP. I suggest that you use TCP, not UDP, in your case.