在Qt中通过TCP传输大文件

问题描述 投票:0回答:2

我是通过套接字传输 TCP 文件的新手。因此,就自我学习而言,我想修改示例“Loopback”,使其在建立连接后从服务器向客户端发送一个大文件(例如 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:请注意代码上的标记<-WHAT HERE!!!->

c++ qt sockets tcp
2个回答
4
投票

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

buffer = file->read(PayloadSize);

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


0
投票

https://stackoverflow.com/beta/discussions/78209992/qt-large-files-into-chunks

您好,先生/小姐,您能帮我一下吗?这是我遇到过的Qt相关问题。

© www.soinside.com 2019 - 2024. All rights reserved.