PDA

View Full Version : Problem with TCP server/client (corrupted data)



chris15001900
11th October 2011, 19:38
Hi,
I'm developing a tcp-based server/client. I found a code to post a struct through tcp, but the data I get is looking weird. Here is what I have right now:




struct abc {
char a;
char b;
};

abc *a = (abc*)malloc(sizeof(struct abc));
a->a='1';
a->b = '2';

QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);

out << (void*)a;

socket->write(block.data());



And here is the code to receive it:



char *data = (char*)this->socket->readAll().data();

QDataStream in(data);
in.setVersion(QDataStream::Qt_4_0);

QByteArray block;
in >> block;

abc *received;
received = (abc*)data;



And when I debug this data, there are many strange characters instead of chars... What can be wrong?

wysota
11th October 2011, 20:58
You are sending a pointer, that's probably not what you want since the pointer will point to a random location after it is received.

chris15001900
11th October 2011, 21:58
Thanks for the reply,
if I don't want a pointer, I can only send it through a reference, and the problem is the same (garbage data):




abc a;
a.a = '1';
a.b = '2';

out << &a;

socket->write(block.data());



Is there a way not to use a reference?

wysota
11th October 2011, 22:12
That's not the point. Using "&a" you are still sending a pointer (and not a reference). You need to send the data, for instance:


struct abc {
char a;
char b;
};

QDataStream& operator<<(QDataStream& stream, const abc &object) {
stream << object.a << object.b;
return stream;
}


QDataStream& operator>>(QDataStream& stream, abc &object) {
stream >> object.a >> object.b;
return stream;
}
and then you can do:

abc a;
a.a = '1';
a.b = '2';
QByteArray data;
QDataStream str(&data);
str << a;
socket->write(data); // btw. such code is practically useless,
// the receiver doesn't know how much data to expect

Being lazy and trying to dump a memory block directly into the data stream is usually a bad idea.

chris15001900
16th October 2011, 09:51
Finally, I got the answer:




struct abc {
char a;
char b;
};

abc *ab;
ab = new abc;

socket->write((char*)ab, sizeof(struct abc));



Works perfect!

Oh, and I receive data like this:




abc *received;

QByteArray data = socket->readAll();

received = (abc*)data.data();

wysota
16th October 2011, 14:29
You are aware that your solution is not portable, right? Probably even between 32 and 64b platforms.