You are not logged in.

1

Tuesday, October 11th 2011, 8:25pm

Problem with TCP server/client (corrupted data)

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:

Source code

1
2
3
4
5
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:

Source code

1
2
3
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?

2

Tuesday, October 11th 2011, 10:19pm

what is the point of

ByteArray block; in >> block;

?

shouldn't you use

Source code

1
QByteArray block;     in >> block;          abc *received;     received = (abc*)block.data();

?

I'm not sure if it will help or not. How do you know your data succesfulyl got to the receiving socket?


You should post COMPLETE example so that others can compile and debug.
If you have a problem, CUT and PASTE your code. Do not retype or simplify it. Give a COMPLETE and COMPILABLE example of your problem. Otherwise we are all guessing the problem from a fabrication where relevant details are often missing.

3

Sunday, October 16th 2011, 9:54am

Finally, I got the answer:

Source code

1
2
3
4
5
6
7
8
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:

Source code

1
2
3
4
5
abc *received;

QByteArray data = socket->readAll();

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

4

Sunday, October 16th 2011, 5:53pm

great. apart from your memory leak...
If you have a problem, CUT and PASTE your code. Do not retype or simplify it. Give a COMPLETE and COMPILABLE example of your problem. Otherwise we are all guessing the problem from a fabrication where relevant details are often missing.

Similar threads

Used tags

client, corrupted, data, qt, server, tcp