aspose file tools*
The moose likes Sockets and Internet Protocols and the fly likes DatagramPacket to String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "DatagramPacket to String" Watch "DatagramPacket to String" New topic
Author

DatagramPacket to String

Ed Thompson
Ranch Hand

Joined: Jan 20, 2006
Posts: 43
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?


Even if the voices <i>aren't</i> real, they still have some good ideas!
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265

If all else fails, you can trim your String:



There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

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.


apigee, a better way to API!
Ed Thompson
Ranch Hand

Joined: Jan 20, 2006
Posts: 43
Natish, how do I get the number of bytes received? If I knew that, my problem would be solved.
Ed Thompson
Ranch Hand

Joined: Jan 20, 2006
Posts: 43
Found it - getLength() on the DataGram packet.

I knew it had to be simple!
 
Consider Paul's rocket mass heater.
 
subject: DatagramPacket to String