I doing TCP file client-server inside single application.
Primarily, I send filename and file's peaces per 50000 bytes.
Client:
void client::sendFile(QString path)
{
QDataStream out(cl);
QFile toSend(path);
if (toSend.open(QIODevice::ReadOnly))
{
int s = 0;
QFileInfo fileInfo(toSend.fileName());
QString fileName(fileInfo.fileName());
out << fileName;
while (!toSend.atEnd())
{
QByteArray rawFile;
rawFile = toSend.read(50000);
out << rawFile;
qDebug() << "ToSend"<<rawFile.size();
s+=rawFile.size();
}
qDebug() << "Total:" << s;
}
}
... this is correct i guess
Server (ReadyRead slot):
void server::receive()
{
QTcpSocket *sender = (QTcpSocket*) this->sender();
QDataStream in(sender);
QString fName;
in >> fName;
QFile newFile("D:\\"+fName);
if (newFile.open(QIODevice::WriteOnly))
{
while(sender->bytesAvailable())
{
QByteArray z;
in >> z;
newFile.write(z);
qDebug () << "Received " << z.size();
}
newFile.close();
}
}
... and here's problem: while
broken after first itteration.
Look:
ToSend 50000
ToSend 50000
ToSend 50000
ToSend 31135
Total: 181135
Received 50000
As you see, only 1 block received instead of 4.
How to fix this? Why bytesAvailable
returns 0 when it's shouldn't?
Would be fine to know is this nice approach to receive files over tcp or not as well :)