• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DatagramPacket to String

 
Ed Thompson
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I create a UDP packet with a byte array of 1024 bytes. When I receive the message, I convert the byte array to a String using:

new String(b, 20, b.length - 20);

However, what I get is the expected String data padded on the right with nulls(?) out to the end of the 1024 bytes, instead of to the end of the byte array actually sent.

What is the correct/standard way to accomplish what I am trying to do?
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If all else fails, you can trim your String:

 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ed: However, what I get is the expected String data padded on the right with nulls(?) out to the end of the 1024 bytes, instead of to the end of the byte array actually sent.

do you mean that the string is padded with blanks?
The constructor you are using, uses the platform default encoding, is that what you want? if not then use a constructor that also takes the charset name.
Also, check the length of the byte array you are sending to the constructor. You must only send the bytes that are received and not the complete byte array.
 
Ed Thompson
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Natish, how do I get the number of bytes received? If I knew that, my problem would be solved.
 
Ed Thompson
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Found it - getLength() on the DataGram packet.

I knew it had to be simple!
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic