How to stop Java from truncating 32bit int to single byte over java.net.Socket ? Or maybe use something else?

0

So the code is really as simple as it gets

int len = 0x00000097;
Socket sock = new Socket(host, port);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.write(i);
out.flush();
out.write(xml_doc);
out.flush();

So the idea is that the host is expecting an xml form but its length before hand. The form is a mere 151 bytes and the host is expecting its length as a 4 byte integer, which I believe is the size of an integer in Java anyway, but no matter which of the stream and print and write varieties and combinations I try, WireShark says on the wire my packet contains one byte, the leading zeroes truncated leaving only <97>. I need a fresh pair of eyes guys ! Please and thanks.

java
sockets
tcp
asked on Stack Overflow Oct 31, 2014 by confusedrussian1 • edited Oct 31, 2014 by Jon Skeet

1 Answer

2

You're calling DataOutput.write(int) on the DataOutputStream, which is documented as:

Writes to the output stream the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

I suspect you really want writeInt:

Writes an int to the underlying output stream as four bytes, high byte first. If no exception is thrown, the counter written is incremented by 4.

So:

out.writeInt(i);

Always check the Javadoc of the methods you're using, particularly when they don't behave the way you expect them to.

answered on Stack Overflow Oct 31, 2014 by Jon Skeet • edited Oct 31, 2014 by Jon Skeet

User contributions licensed under CC BY-SA 3.0