在 Qt 中通过 TCP 传输大文件

Posted

技术标签:

【中文标题】在 Qt 中通过 TCP 传输大文件【英文标题】:Transferring large files over TCP in Qt 【发布时间】:2014-11-21 16:01:59 【问题描述】:

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

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(&amp;file, QIODevice::WriteOnly);)。

谢谢!

PD:请注意代码上的标记

【问题讨论】:

只需将文件复制为中等大小的块(例如,每个 64 KB) 【参考方案1】:

好的,感谢Basile Starynkevitch,我找到了解决方案。 就这么简单:

buffer = file->read(PayloadSize);

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

【讨论】:

以上是关于在 Qt 中通过 TCP 传输大文件的主要内容,如果未能解决你的问题,请参考以下文章

Windows下基于TCP协议的大文件传输(流形式)

Windows下基于TCP协议的大文件传输(流形式)

TCP协议传输大文件读取时候的问题

如何用Qt的Qudpsocket传输图片文件?

labview编程tcp传输大文件时突然断开

QT应用编程: 基于UDP协议设计的大文件传输软件