I am newbie on TCP file transferring over sockets. So just in terms of self-lerning, I want to modify the example "Loopback" to make it send a large file (e.g 100Mb to 2Gb) from server to client once the connections is established. My problem is that I have no idea how to split the file in order to now when the transmission has to finish. Let me insert a piece of code to make this easier to understand:
server.cpp
void Dialog::acceptConnection()
{
tcpServerConnection = tcpServer.nextPendingConnection();
connect(tcpServerConnection,SIGNAL(connected()), this, SLOT(startTransfer()));
connect(tcpServerConnection, SIGNAL(bytesWritten(qint64)), this, SLOT(updateServerProgress(qint64)));
connect(tcpServerConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
serverStatusLabel->setText(tr("Accepted connection"));
startTransfer();
}
void Dialog::startTransfer()
{
file = new QFile("file_path");
if (!file->open(QIODevice::ReadOnly))
{
serverStatusLabel->setText("Couldn't open the file");
return;
}
int TotalBytes = file->size();
bytesToWrite = TotalBytes - (int)tcpServerConnection->write(<-WHAT HERE!!!->));
serverStatusLabel->setText(tr("Connected"));
}
void Dialog::updateServerProgress(qint64 numBytes)
{
bytesWritten += (int)numBytes;
// only write more if not finished and when the Qt write buffer is below a certain size.
if (bytesToWrite > 0 && tcpServerConnection->bytesToWrite() <= 4*PayloadSize)
bytesToWrite -= (int)tcpServerConnection->write(<-WHAT HERE!!!->));
serverProgressBar->setMaximum(TotalBytes);
serverProgressBar->setValue(bytesWritten);
serverStatusLabel->setText(tr("Sent %1MB").arg(bytesWritten / (1024 * 1024)));
}
I've seen some solution that use readAll()
but I don't think qt can handle a buffer with 2Gb of data inside...
So, as mentioned, my question is how to slip up the file to by write over tcpServerConnection
? I would like to know if it's recommended to use QDataStream for that purpose (QDataStream out(&file, QIODevice::WriteOnly);
), as well.
Thanks!
PD: Note the mark <-WHAT HERE!!!-> on the code.
Ok, thanks to Basile Starynkevitch I find out the solution. It's as easy as set:
buffer = file->read(PayloadSize);
And then send it through Tcp. In local network I achieve to transfer 397Mb in 40.11 sec. Thanks,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With