Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

DatagramPacket::getLength() does not refresh  RSS feed

 
Victor Ho
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Not sure if this has been posted before. When I try to reuse the same DatagramSocket object to listen on incoming data, the value of getLength() does not get updated!
e.g.
byte buf[] = new byte[8192];
DatagramPacket packet = new DatagramPacket(buf,buf.length);
socket.receive(packet); // 1st receive (I send 8 bytes from the other side)
// If I do packet.getLength() it returns the accurate # bytes received (i.e. 8)
socket.receive(packet); // 2nd receive (I send 30 bytes from the other side)
// If I do packet.getLength() now, it still returns me 8 instead of 30.
Has anyone encountered similar problems? I am using JDK 1.3.1
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that receive() uses the "length" in the DatagramPacket as an input indicating the upper bound on the number of bytes that will be read, as well as an output indicating the numebr that actually were read. Initially, you have the length set to 8192; then you read an 8 byte packet, the length is set to 8. Now if you try to receive a 30 byte packet, it's truncated to 8 bytes, as that's the value the length had when receive was called.
The solution: use setLength() to put the length back to 8192 before each receive call.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!