I'm writing a simple TCP based network application in Qt and wanted to use QDataStream
and QByteArray
to send data over the network. The problem is that when I'm putting data into QByteArray
they are "zeroed". For example (a slot in MainWindow
that is connected to timer timeout signal):
void MainWindow::SendPlayer1Data(){
QByteArray block;
QDataStream s(&block, QIODevice::OpenModeFlag::ReadWrite);
QString h="hello";
s<<h;
qDebug() << "h: " << data;
qDebug() << "block: " << QString(block); // equivalent to s >> h on receiving end
qDebug() << "block[0]: " << int(block[0]);
}
h: "hello"
block: ""
block[0]: 0
I receive "hello"
once at the beginning but after that I only get ""
. The same goes for qint32
. Both client and server shows that QByteArray
size is 14 bytes, so QDataStream
writes data into that array, but it makes them 0
(it shows ""
when I use s >> h
and then use qDebug() << h
)
Ok, I have figured it out.
The problem was not the QByteArray
or socket because, as @William Miller
mentioned, the data was there.
The problem was with QDataStream
on client side - I decided to create a new QDataStream
object every time the slot responsible for receiving data was called. This way I was able to pack data easily into QByteArray
, send it and receive every time.
The client function for receiving:
void ClientTcpHelper::ReceivePacket(){
if(socket.waitForReadyRead(20)){
//qDebug()<<"Packet: "<<socket.peek(30)<<endl;
qDebug()<<"Receiving packet!"<<endl;
Data=socket.readAll();
emit DataReceived();
}
else{
//qDebug()<<"Failed to receive packet!"<<endl;
}}
and unpacking data to variables:
void ClientTcpHelper::UnpackData(){
stream=new QDataStream (&this->Data,QIODevice::OpenModeFlag::ReadWrite);
*stream>>h>>a>>b;
Data.clear();
delete stream;}
h,a and b are members of a class.
Unfortunately I can not explain why QDataStream
need to be destroyed every time here in order to handle data as I wanted it from the beginning.