3

我正在创建一个小型 TFTP 客户端服务器应用程序,其中服务器使用 c++ 开发,客户端使用 java 开发。

在这里,我使用 htons转换发送“块计数”值。

但我无法将其转换回客户端的原始值。

例如,如果我正在 ntohs(01)从服务器向客户端发送块计数(2 个字节)。客户端正在读取字节。我收到的值是字节 0 和字节 1。

请如果有人可以提供解决方案。

4

3 回答 3

3

我认为您的意思是您ntohs用来解码从网络读取的值,并对通过网络发送的值htons进行编码

ByteBuffer#getShort()一起来看ByteBuffer#order(ByteOrder)网络字节顺序big endian,因此请使用该值ByteOrder#BIG_ENDIANByteBuffer正确配置。请注意,这BIG_ENDIAN是默认顺序,但在这种情况下,最好明确说明您的偏好。


您没有提到您在 Java 中用于网络通信的内容。如果是 a java.net.Socket,您可以调用Socket#getChannel()来获取 ajava.nio.channels.SocketChannel的子类型java.nio.channels.ByteChannel,您可以使用它ByteBuffer来读取和写入数据。

于 2009-11-26T01:18:01.350 回答
1
   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();
    }
于 2009-12-01T20:20:18.853 回答
0

Java 的内部数字始终按网络字节顺序排列,即使在本机整数/双精度不是的系统上也是如此。这意味着您可以使用执行这种转换的任何基本输入流(实现 java.io.DataInput)将任何传入的数字转换为 Java。如果您使用的是 java.nio.Channel,ByteBuffer 也可以工作,但您可以更改字节顺序 ( ByteBuffer.order()),尽管默认值对于网络字节排序和 Java 内部存储是正确的。

顺便说一句,我认为您的意思是使用htons,但在您展示的示例中ntohs。从 C++ 发送您想要将主机订单转换为网络订单。从 Java(或任何客户端)接收您的服务器将使用ntohs.

于 2009-11-27T00:01:02.900 回答