简体   繁体   中英

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.

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.

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);

如果要发送少量数据,则编码为字符数据(例如Integer.toString(length) )并在另一端进行解码并非不合理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM