c ++ server htons to java ntohs客户端转换 [英] c++ server htons to java ntohs client conversion

查看:159
本文介绍了c ++ server htons to java ntohs客户端转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a small TFTP client server app where server is developed using c++ and client using java.

但是我无法将它转换回来,因此使用 htons
到客户端的原始值。

But i am not able to convert it back to its original value at client.

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

For example if am sending block count ntohs(01) (2 bytes) from server to client. Client is reading in bytes. Value which I am receiving is byte 0 and byte 1.

如果任何一个可以提供
解决方案。 p>

Please if any one can provide a solution.

推荐答案

我认为你的意思是你使用 ntohs 从网络读取的值, htons 编码通过网络发送的值。

I take it you meant that you use ntohs to decode the values read from the network, and htons to encode the values sent over the network.

查看 ByteBuffer#getShort() ByteBuffer#order(ByteOrder) 网络字节顺序 big endian ,因此请使用 ByteOrder#BIG_ENDIAN 配置 ByteBuffer 正确。请注意, BIG_ENDIAN 是默认顺序,但在这种情况下,显式地陈述您的偏好是很好的形式。

Look into ByteBuffer#getShort() in concert with ByteBuffer#order(ByteOrder). Network byte order is big endian, so use the value ByteOrder#BIG_ENDIAN to configure your ByteBuffer properly. Note that BIG_ENDIAN is the default order, but in this case it would be good form to state your preference explicitly.


您没有提及您在Java中使用网络通信。如果它是一个 java.net.Socket ,你可以调用 Socket#getChannel()得到 java.nio.channels.SocketChannel java.nio.channels.ByteChannel 的子类型,您可以使用 ByteBuffer 读取和写入数据。

You didn't mention what you're using for network communications in Java. If it's a java.net.Socket, you can call Socket#getChannel() to get a java.nio.channels.SocketChannel, a subtype of java.nio.channels.ByteChannel, with which you can use ByteBuffer to read and write data.

这篇关于c ++ server htons to java ntohs客户端转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆