I wrote a server using c++ and the code looks like this
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
write(client->getFd(), sendBuffer, MAX_LENGTH);
Client is written in 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.
How do I fix this ? Thanks in advance..
Pretty simple, really: you want to add your
offsetto the destinationsendBuffer, not your sources. E.g. instead ofyou want
As it is, you are storing various random data to the first few bytes of
sendBuffer, and nothing to the rest of it.