c ++ server htons to java ntohs client conversion
-
05-07-2019 - |
题
我正在创建一个小型TFTP客户端 开发服务器的服务器应用程序 使用c ++和客户端使用java。
我在这里发送“块计数”值
使用 htons
转换。
但我无法将其转换回来 在客户端的原始价值。
例如,如果发送块计数
从服务器到的 ntohs(01)
(2个字节)
客户。客户端以字节为单位读取。
我收到的值是字节0
和字节1。
如果有人可以提供 溶液
解决方案
我认为你的意思是你使用 ntohs
来解码从网络读取的值, htons
到 encode 通过网络发送的值。
查看 <代码> ByteBuffer#getShort() 与 ByteBuffer #order(ByteOrder)
。 网络字节顺序是 big endian ,因此请使用值 ByteOrder #BIG_ENDIAN
正确配置 ByteBuffer
。请注意, BIG_ENDIAN
是默认顺序,但在这种情况下,明确说明您的偏好是一种很好的形式。
您没有提到您在Java中使用的网络通信内容。如果它是 java.net.Socket
,您可以调用 Socket#getChannel()
来获取 java.nio.channels.SocketChannel
, java.nio.channels.ByteChannel
的子类型,您可以使用 ByteBuffer
来读取和写入数据。
其他提示
private void somemethod(){
byte[] fileDataFull = new byte[516];
byte[] receivedCounter = new byte[2];
readLength = in.read(fileDataFull);
receivedCounter[0] = fileDataFull[2];
receivedCounter[1] = fileDataFull[3];
if (expectedPktCount == convertntohs(receivedCounter)){
}
byte[] b = converthtons((short) expectedPktCount);
}
private short convertntohs(byte[] value) {
ByteBuffer buf = ByteBuffer.wrap(value);
return buf.getShort();
}
private byte[] converthtons(short sValue) {
byte[] baValue = new byte[2];
ByteBuffer buf = ByteBuffer.wrap(baValue);
return buf.putShort(sValue).array();
}
Java内部的数字始终按网络字节顺序排列,即使在本机整数/双精度数不存在的系统上也是如此。这意味着您可以将任何进入Java的数字转换为执行此类转换的任何基本输入流 - 实现java.io.DataInput。如果您使用java.nio.Channel,ByteBuffer也可以工作,但您可以更改字节顺序( ByteBuffer.order()
),但默认情况下,网络字节排序和Java内部存储是正确的。 / p>
顺便说一句,我认为您的意思是使用 htons
,但在示例中您显示 ntohs
。从C ++发送您要将 h ost order转换为 n etwork order。从Java(或任何客户端)接收服务器将使用 ntohs
转换回来。