简体   繁体   English

在Java中通过socket发送int

[英]Sending int through socket in Java

What is the best possible way to send an int through a socket in Java? 在Java中通过套接字发送int的最佳方法是什么? 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. 然后尝试从另一侧的字节重建int,但它似乎不起作用。 Any ideas? 有任何想法吗?

Thanks. 谢谢。

Wrap your OutputStream with a DataOutputStream and then just use the writeInt() method. 使用DataOutputStream包装OutputStream ,然后使用writeInt()方法。

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. 可能有用的其他东西是另一端你可以将我们的InputStream包装在DataInputStream中并使用readInt()来读取一个int

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. 您可以使用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) )并在另一端进行解码并非不合理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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