Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending int through socket in Java

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.

like image 333
user174772 Avatar asked Sep 17 '09 06:09

user174772


1 Answers

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.

like image 136
Adam Batkin Avatar answered Nov 15 '22 15:11

Adam Batkin