strange Java problem

Status
You're currently viewing only Marco H's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

Marco H

Smack-Fu Master, in training
69
hi all,

i encountered a strange problem while writing a simple UDP client-server pair which cost me nearly an hour to track down.

i have my class UDPServer which waits for a datagram from the client and will then send a string back. I build the string using a string buffer like this:

Code:
  tstamp = new java.sql.Timestamp(date.getTime());
  Calendar now = Calendar.getInstance();
  int seconds = now.get(Calendar.SECOND);
  strbuf.append(rcvString).append(seconds).append(tstamp.getNanos());

  // i now pass the stringbuffer to a bytebuffer
  byte[] bufnew = new byte[256];
  bufnew = strbuf.toString().getBytes();

  packet = new DatagramPacket(bufnew, bufnew.length, addr, 1201)
 
  socket.send(packet)

Now this looks like it should work, only it doesn't.
The client only receives the first part of the strbuf (rcvString) and doesn't get the rest.

but now comes the best part:
when i simply change the order in which i append stuff to the stringbuffer like so:

Code:
 strbuf.append(tstamp.getNanos()).append(seconds).append(rcvString));

it works, wtf is going on there :confused: :confused:

maybe i am just dense, but i can't see what goes wrong.
btw i use netbeans 3.3.1 under linux (don't know if this matters)

so, anyway, maybe one of you can figure out where this behaviour comes from.

thanks in advance
 

Marco H

Smack-Fu Master, in training
69
but how would it be relevant what size rcvString (4 characters) has.

i call
Code:
 strbuf = new Stringbuffer()
therefor i get a stringBuffer with 1024 bytes allocated space, right?
(i should have that included to avoid misinterpretation, my fault)

and if necessary the stringbuffer is able to grow if i'm not mistaken.

also, when i fill the stringBuffer "backwards" i get the result i have expected not only X+N characters with some being truncated.

and the datagramPacket should have plenty of space (256 byte):
Code:
  byte[] bufnew = new byte[256];
  bufnew = strbuf.toString().getBytes();
  packet = new DatagramPacket(bufnew, bufnew.length, addr, 1201)

so that does not seem to be the reason for this behaviour.

maybe that clarifies the situation a little bit.
 
Status
You're currently viewing only Marco H's posts. Click here to go back to viewing the entire thread.
Not open for further replies.