PDA

View Full Version : How to send my own memory buffer via QTcpSocket and QTcpServer?



fulin
22nd March 2010, 10:06
Hello,

I'm a newbie to QT . Can anyone give me some hints on how I can send my own memory buffer which contains a rather complicated data structure via QTcpSocket or QTcpServer?

Here is what I'm trying. But it seems not work.

Thank you for your help in advance!

//QBuffer buffer;
QByteArray buffer;
QDataStream out(&buffer, QIODevice::WriteOnly);
char *to =(char*) buffer.data().data();
memcpy(to,&myOwnBufffer, myOwnBufferSize);
out.device()->seek(0);
out << (quint16)(buffer.size() - sizeof(quint16));
tcpSocket->write(buffer);

myOwnBuffer is a structure<-structures<-structures (contains several data type).

wysota
22nd March 2010, 12:34
First of all be aware that if your data structure contains any pointers or non-POD objects (like classes), you will receive garbage on the receiving end.

Now that you have been warned...

The easiest way to do what you want is:

socket->write((const char*)&myOwnBuffer, myOwnBufferSize);

fulin
22nd March 2010, 13:59
Thank you, wysota. It works well.

For receiving data, I'm thinking about doing the same way

socket->read(&myReceiveBuffer, myDataMaxSize);

Just do not know how to decide myDataMaxSize. It seems that I must know what is the expected data in advance. For the QByteArray data, the QTcpSocket seems can know the max size.

wysota
22nd March 2010, 16:01
In general the way you are doing it is a wrong approach. A good approach would be to implement streaming operators to and from QDataStream for your structure and use that instead of sending raw data over network.

fulin
22nd March 2010, 18:32
Yes, you are right.

But here it is for coping with our legacy native C code.