Stephan van Hulst wrote:Okay, it works that way because the datagram uses receiveBuffer as it's internal memory. It will only overwrite the bytes that it needs for the new message, and then set a separate integer to say how long the received message was. This is cheaper than replacing its internal memory with a newly constructed array of bytes.
What you can do, is use Arrays.copyOf() to get a new array from the receiveBuffer which matches the length of the message you received, and then constructing a String out of that. Another option (if you're running a Java version older than 6) is constructing the String out of the receiveBuffer like you do now, and then using String.substring() to distill the received message out of it. Your code, like you said, works, but these are alternatives to using the StringBuffer, which I think is a bit clunky for your purpose.