来自C ++ Client的Java DataInputStream readInt()获得巨大价值 [英] Java DataInputStream readInt() from C++ Client getting huge value

查看:165
本文介绍了来自C ++ Client的Java DataInputStream readInt()获得巨大价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑这与字节序有关,但我不确定如何修复它。我有一个C ++客户端告诉Java服务器它将要发送多少字节,Java服务器只在输入流上调用readInt()。然后服务器继续读取剩余的数据。

I suspect this has to do with endianness but I'm not sure how to fix it. I have a C++ client telling a Java server how many bytes it's about to send where the Java server just calls readInt() on the input stream. Then the server goes onto read the rest of the data.

目前,如果C ++服务器调用:

At the moment if the C++ server calls:

char l = '3';
BytesSent = send( Socket, &l, 1, 0 );

然后相应的Java方是:

Then the corresponding Java side is:

int lBytesSent = m_InDataStream.readInt();

m_AckNack = new byte[lBytesSent];
m_InDataStream.read(m_AckNack)

字节lBytesSent往往是一个巨大的价值然后只是在创建数组时引发异常(不出意料)

Bytes lBytesSent tends to be some massive value which then just throws an exception when it comes to creating the array (not surprisingly)

C ++套接字只需打开:

The C++ socket is simply opened up with:

Socket = socket(AF_INET, SOCK_STREAM, 0);
Option = 1000;
setsockopt(Socket, SOL_SOCKET, SO_RCVTIMEO, (char *) &Option, sizeof(Option));
server.sin_family = AF_INET;
server.sin_port = htons(Port);
server.sin_addr.s_addr = INADDR_ANY;
memset(&(server.sin_zero), '\0', 8);
connect(Socket, (sockaddr*)&server, sizeof(server));

Java方面:

ServerSocket listener = new ServerSocket(port);
Socket server;
server = listener.accept();

删除错误检查以确保清晰。

Removing the error checking for clarity.

任何建议都会很棒

非常感谢

马克

推荐答案

尝试通过 htonl 在发送之前(在C ++端):

Try running the number through htonl before sending it (on the C++ side):

long x = htonl(42); /* x now contains 42 represented in network byte order */

这篇关于来自C ++ Client的Java DataInputStream readInt()获得巨大价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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