Witam, muszę wysłać plik przez TCP od Clienta do Servera. Wpomagałem się przeróżnymi stronami(głównie jakimś niepełnym gist)i udało mi się zrobić coś takiego:
Client, wysyłanie pliku:
QFile *file= new QFile("in.txt");
file->open(QIODevice::ReadOnly);
int filesize = file->size();
//We'll send the file in chunks of 64k (short of). We don't want to fill the memory at once if it's a large file
qint64 chunk = 64000;
qint64 filepos=0; //Position for reading/writing
while (filepos < filesize)
{
char *data = new char[chunk];
qint64 length = file->read(data, chunk);
socket->write(data,length); //Send read data
filepos += length; //Go to new position depending what we read
delete [] data;
}
file->close();
delete file;
oraz zapisywanie tego przez serwer, myślę, że tutaj jest jakiś problem:
Najpewniej brakuje mi jakiegoś połączenia, gdy chiałem to wyoływać z użyciem readReady(), nie wywoływało tego, a gdy wywołuję ręcznie od razu z sygnału NewConnection() to socket->bytesAvailable() zwraca 0 i program się kończy.
QDataStream in(socket);
in.setVersion(QDataStream::Qt_5_8);
quint64 blockSize=0;
/*******************Reading the blockSize first in order to know how much data we'll receive***/
if (blockSize == 0)
{
if (socket->bytesAvailable() < (int)sizeof(quint64)){
return;
}
in >> blockSize;
}
if (socket->bytesAvailable() < (int) blockSize) //Wait until all the data are received
return;
in >> filesize;
file = new QFile("in.txt"); //Create the file
file->open(QIODevice::WriteOnly); //Open it
//Download it in chunks, so the memory won't crash
char *data = new char[buffer];
length = socket->read(data, buffer); //Buffer 1MB first, max.
file->write(data,length);
sizeread += length;
delete [] data;
if (sizeread == filesize) //File size reached, closing file
{
file->close();
delete file;
counter++;
length=0;
sizeread=0;
}