user1880760
user1880760

Reputation: 59

UDP socket programming(extracting the data, storing it in a string)

I am learning about TCP and UDP socket programming with Java, one of the books i am reading for my networking class has the following line:

DatagramPacket receivedPacket = new DatagramPacket(receiveData, receiveData.length);

String modifiedSentence = new String(receivedPacket.getData());

Where receivedPacked is just a DatagramPacket type Object and modifiedSentence stores what was returned from the server. ReceivedPacket.getData() converts the packet from bytes to the string in this case before storing it.

My question is why create an object of a string and storing/passing the converted packet to it rather than using the following:

String modifiedSentence = receivedPacket.getData();

Would this not work? I thought in Java it was impractical to specifically create an object of the String class.

Upvotes: 1

Views: 1413

Answers (2)

user207421
user207421

Reputation: 310957

String modifiedSentence = new String(receivedPacket.getData())

That's wrong anyway. It should be

String modifiedSentence = new String(receivedPacket.getData(), 0, receivedPacket.getLength())

My question is why create an object of a string and storing/passing the converted packet to it rather than using the following:

String modifiedSentence = receivedPacket.getData();

Because it doesn't compile. getData() returns byte[], not a String.

I thought in Java it was impractical to specifically create an object of the String class.

Only if the argument already is a String. In this case it isn't.

Upvotes: 0

Pete
Pete

Reputation: 6723

DatagramPacket.getData() returns a byte array not a string. Thus you need to convert it to a string to assign it to a string.

Upvotes: 2

Related Questions