在Qt中通过TCP传输大文件

Transferring large files over TCP in Qt

本文关键字:传输 文件 TCP Qt      更新时间:2023-10-16

我是通过套接字传输TCP文件的新手。因此,就自我转换而言,我想修改示例"环回",使其在建立连接后从服务器到客户端发送大文件(例如 100Mb 到 2Gb)。我的问题是我不知道如何拆分文件以便现在传输必须完成。让我插入一段代码,使其更容易理解:

服务器.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:注意标记<-这里是什么!!->代码上。

好的,多亏了Basile Starynkevitch,我找到了解决方案。就像设置一样简单:

buffer = file->read(PayloadSize);

然后通过 Tcp 发送。在本地网络中,我实现了在40.11秒内传输397Mb。谢谢