[英]Can not read byte data from inputstream
I wrote a server using c++ and the code looks like this我使用 c++ 编写了一个服务器,代码如下所示
char *sendBuffer = new char[4+4+1+8+48];
m_magicNumberBuffer[0] = 0xA9;
m_magicNumberBuffer[1] = 0xA9;
m_magicNumberBuffer[3] = 0xA9;
m_magicNumberBuffer[4] = 0xA9;
int m_dataLength = 4+4+1+8+48;
unsigned char m_type = 1;
long long m_deviceId = 12123122123;
char m_msg = new char[48];
m_msg = "NO ERROR";
/*
* Magic number;
*/
memcpy(sendBuffer, m_magicNumberBuffer + offset, 4);
offset += 4;
/*
* Data length
*/
memcpy(sendBuffer, &m_dataLength + offset, 4);
offset += 4;
/*
* Packet type
*/
memcpy(sendBuffer, &m_type + offset, 1);
offset += 1;
/*
* Device ID
*/
memcpy(sendBuffer, &m_deviceId + offset, 8);
offset += 8;
memcpy(sendBuffer, m_msg + offset, 48);
offset += 48;
I am writing the sendBuffer我正在写 sendBuffer
write(client->getFd(), sendBuffer, MAX_LENGTH);
Client is written in Java客户端写在 Java
I am doing something like this我正在做这样的事情
InputStream in = mSocket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int magicNumber = dis.readInt();
int length = dis.readInt();
byte[] data = new byte[length];
if(length > 0){
dis.readFully(data);
}
And it reads something wrong.它读错了。 I am getting unreasonable number for the magic number and always reads 0 for the data length.我得到的幻数数字不合理,并且数据长度始终为 0。
How do I fix this?我该如何解决? Thanks in advance..提前致谢..
Pretty simple, really: you want to add your offset
to the destination sendBuffer
, not your sources.非常简单,真的:你想将你的offset
添加到目标sendBuffer
,而不是你的源。 Eg instead of例如,而不是
memcpy(sendBuffer, &m_deviceId + offset, 8);
you want你要
memcpy(sendBuffer + offset, &m_deviceId, 8);
As it is, you are storing various random data to the first few bytes of sendBuffer
, and nothing to the rest of it.实际上,您将各种随机数据存储到sendBuffer
的前几个字节,而没有存储到它的 rest 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.