[SOLVED]Need Help:structure over socket
-
I don't quite get the roundtrip through QByteArray, to be honest. QStreamWriter can operate directly on the socket...
Anyway, I will assume your implementation of the streaming operator for your structName is still like this:
@
QDataStream &operator <<(QDataStream &out,const structName &dataStruct)
{
out << dataStruct.varint;
out.writeRawData ( dataStruct.varchar, 10 );
return out;
}
@Here, you first output the int. You are using a plain int, but I'd recommend to always use variables with a guaranteed size for these purposes. int normally is the same as qint32. So, you have a 32 bits (four bytes) value. You will need to send all of these bytes in the stream. If your value has a smaller range, you should use a smaller data type like quint16 or qint8. Otherwise, on the receiving side, there is no way to know how to read in the data again. Note that this is binary data, not text that you are seeing.
-
/teacher mode...
QDataStream is a class that is meant to operate on a [[doc:QIODevice]]. The socket is such an IO device. If you use it on a QByteArray, it actually creates a [[doc:QBuffer]] in the background. QBuffer is a class that provides a QIODevice interface on a QByteArray.
-
@struct your_structure
{
//variables
},test@When you want to send the structure:
@char * sendPack = (char *)&test;
writeDatagram((const char *)sendPack,sizeof(your_structure),destIP,destPORT);@When you want to receive the packet:
@char recPack[sizeof(your_structure)];
readDatagram((char *)&inPack, sizeof(your_structure),senderIP, senderPort);
your_structure * inp = new your_structure();
inp = (your_structure *)inPack;@ -
[quote author="vahidnateghi" date="1383463791"]@struct your_structure
{
//variables
},test@When you want to send the structure:
@char * sendPack = (char *)&test;
writeDatagram((const char *)sendPack,sizeof(your_structure),destIP,destPORT);@When you want to receive the packet:
@char recPack[sizeof(your_structure)];
readDatagram((char *)&inPack, sizeof(your_structure),senderIP, senderPort);
your_structure * inp = new your_structure();
inp = (your_structure *)inPack;@[/quote]That won't work if you're on different architectures, like trying to communicate between a 32 bits and a 64 bits version of your application, to name just one possible problem with this approach. My advise: never, ever do it this way.
-
[quote author="Andre" date="1383491720"]
That won't work if you're on different architectures, like trying to communicate between a 32 bits and a 64 bits version of your application, to name just one possible problem with this approach. My advise: never, ever do it this way.
[/quote]Yes,you're right, when I used it and it worked, it was between two machines with the same architecture...