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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With