Hi,
I'm reading from a TCP socket with the code below, i have no knowledge of how much data will be sent, i just know that it will end in a specific termination sequence, so my pseudo code is:
Read available bytes from socket
check end of buffer for termination sequence
Repeat if needed
(im using synchronous sockets, so when the below function is called, i know there should be data ready to recieve)
return false;
do
{
buffer.clear();
if(!socket->waitForReadyRead())
{
socket->disconnect();
qDebug() << "Error: "<< socket->errorString();
file.close();
return false;
}
// read from socket
buffer = socket->readAll();
if(buffer.size() == 0) // empty byte array = bad
{
socket->disconnect();
qDebug("Error: Empty buffer.");
file.close();
return false;
}
file.write(buffer); // Append current buffer chunk to file
// breaks when termination sequence found at end of buffer
} while(!TransmissionFinished(buffer, type));
file.close(); // all done
QByteArray buffer;
QFile file(file_path);
if (!file.open(QIODevice::WriteOnly))
return false;
do
{
buffer.clear();
if(!socket->waitForReadyRead())
{
socket->disconnect();
qDebug() << "Error: "<< socket->errorString();
file.close();
return false;
}
// read from socket
buffer = socket->readAll();
if(buffer.size() == 0) // empty byte array = bad
{
socket->disconnect();
qDebug("Error: Empty buffer.");
file.close();
return false;
}
file.write(buffer); // Append current buffer chunk to file
// breaks when termination sequence found at end of buffer
} while(!TransmissionFinished(buffer, type));
file.close(); // all done
To copy to clipboard, switch view to plain text mode
While this works, after a bit of testing I occasionally get a timeout error which results in corrupt data because a chunk is missing, and there is no real reason why it should timeout in this case which makes me think im not approaching it correctly. So if anyone could tell me if something is clearly incorrect, or if there is a more elegant way of doing this i would really appreciate it.
Many thanks for any help,
Jack
Bookmarks