views:

715

answers:

3

What is the best possible way to send an int through a socket in Java? Right now I'm looking at

sockout.write((byte)( length >> 24 ));
sockout.write((byte)( (length << 8) >> 24 ));
sockout.write((byte)( (length << 16) >> 24 ));
sockout.write((byte)( (length << 24) >> 24 ));

and then trying to rebuild the int from bytes on the other side, but it doesn't seem to work. Any ideas?

Thanks.

+2  A: 

There are other type of streams you can use, which can directly send integers. You can use DataOutputStream. Observe,

DataOutputStream out;
try {
    //create write stream to send information
    out=new DataOutputStream(sock.getOutputStream());
} catch (IOException e) { 
    //Bail out
}

out.writeInt(5);
Cem Kalyoncu
+10  A: 

Wrap your OutputStream with a DataOutputStream and then just use the writeInt() method.

Something else which may be useful is that on the other end you can wrap our InputStream in a DataInputStream and use readInt() to read an int back out.

Both classes also contain a number of other useful methods for reading and writing other raw types.

Adam Batkin
Obviously the way it was meant to be done.
abyx
Only if there's also java of the other end.
tulskiy
A: 

If you are sending small amounts of data, then encoding as character data (e.g. Integer.toString(length)) and decoding at the other end is not unreasonable.

Stephen C