在Java中通过套接字发送int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1436942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:15:13  来源:igfitidea点击:

Sending int through socket in Java

javanetworkingsocketsinteger

提问by user174772

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

在 Java 中通过套接字发送 int 的最佳方法是什么?现在我在看

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?

然后尝试从另一侧的字节重建 int,但它似乎不起作用。有任何想法吗?

Thanks.

谢谢。

回答by Cem Kalyoncu

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

您还可以使用其他类型的流,它们可以直接发送整数。您可以使用 DataOutputStream。观察,

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

out.writeInt(5);

回答by Adam Batkin

Wrap your OutputStreamwith a DataOutputStreamand then just use the writeInt()method.

OutputStreamDataOutputStream包裹你,然后只使用该writeInt()方法。

Something else which may be useful is that on the other end you can wrap our InputStreamin a DataInputStreamand use readInt()to read an intback out.

其他可能有用的是,在另一端,您可以将我们的数据包装InputStreamDataInputStream 中并用于readInt()读取int回传。

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

这两个类还包含许多其他有用的方法,用于读取和写入其他原始类型。

回答by Stephen C

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.

如果您要发送少量数据,那么编码为字符数据(例如Integer.toString(length))并在另一端解码并不是不合理的。