2
我是通过套接字传输的TCP文件的新手。因此,就自我激励而言,我想修改示例“Loopback”,以便在连接建立后,从服务器向客户端发送一个大文件(例如100Mb到2Gb)。 我的问题是,我不知道如何分割文件,直到现在传输完成。 让我插入了一段代码,以使这更容易理解:在Qt中通过TCP传输大文件
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)));
}
我已经看到了一些解决方案,使用readAll()
,但我不认为Qt可以处理2Gb的数据里面的缓冲区... 所以,如上所述,我的问题是如何通过tcpServerConnection
写入文件以上?我想知道是否建议为此目的使用QDataStream(QDataStream out(&file, QIODevice::WriteOnly);
)。
谢谢!
PD:注意标记< -WHAT HERE !!! - >上的代码。
只需将文件复制到中等大小的块(例如每个64 KB) – 2014-11-21 16:36:17