PDA

View Full Version : QTCPsocket data corrupt when receive



gabizzz
3rd March 2010, 02:15
Sorry for my bad english, but iḿ trying to learn the concept of data transfer between qtserver qtcpsocket, but my files on to receive are corrupt. what is wrong? I Need your help please, thanks.:(

gabizzz
3rd March 2010, 11:12
This is the receiver

void Dialog::tcpReady()
{
QFile file("linux.png");
while(socket.bytesAvailable() > 0)
{
QByteArray ar=socket.readAll();
file.open(QIODevice::WriteOnly);
QDataStream ds(&file);
ds.setVersion(QDataStream::Qt_4_6);
ds << ar;
}
file.close();
}

This is the Sender

void ServerThread::run()
{
QTcpSocket socket;
if( !socket.setSocketDescriptor( m_descriptor ) )
{
qDebug( "Socket error!" );
return;
}


QFile file("linux.png");
if (!file.open(QIODevice::ReadOnly))
{
qDebug("Cannot open file!");
return;
}

QByteArray data=file.readAll();
int size=data.size();

QByteArray sizeBytes;
quint32 b= quint32(data.size() - sizeof(quint32));
sizeBytes.append(b);
sizeBytes.append(data);
socket.write(sizeBytes);
socket.waitForDisconnected();
}

Bitto
4th March 2010, 17:29
Hi, gabizzz. The first slot doesn't have to be a loop, as socket.readAll() always reads everything in the buffer.

So instead try this, it should do the same:


void Dialog::tcpReady()
{
QFile file("linux.png");
file.open(QIODevice::WriteOnly + QIODevice::Append);
QDataStream ds(&file);
ds.setVersion(QDataStream::Qt_4_6);
ds << socket.readAll();
file.close();
}

Better check you error conditions though. If the file open fails, your program will misbehave. I slipped in QIODevice::Append, assuming you don't want to overwrite your file for every received packet. For improved performance it's best to leave the file open and not reopen it for each packet though.

The rest of the code looks quite right (I haven't seen the whole source code).