C++ ';内存已满';使用QTcpSocket传输大文件时
我正在尝试以非阻塞方式传输一个大文件,方法是将C++ ';内存已满';使用QTcpSocket传输大文件时,c++,qt,memory-leaks,qtcpsocket,C++,Qt,Memory Leaks,Qtcpsocket,我正在尝试以非阻塞方式传输一个大文件,方法是将BytesWrite连接到我的函数sendNextBlock void AsynchronousRetrieveCommand::start() { connect(socket(), SIGNAL(bytesWritten(qint64)), this, SLOT(sendNextBlock())); sendNextBlock(); } void AsynchronousRetrieveCommand::sendNextBloc
BytesWrite
连接到我的函数sendNextBlock
void AsynchronousRetrieveCommand::start()
{
connect(socket(), SIGNAL(bytesWritten(qint64)), this, SLOT(sendNextBlock()));
sendNextBlock();
}
void AsynchronousRetrieveCommand::sendNextBlock()
{
socket->write(file->read(64*1024));
}
我在Symbian手机上运行此代码,在传输了5-6兆字节后,手机中会出现“内存已满”消息框,调试输出中会出现以下消息:
[Qt Message] CActiveScheduler::RunIfReady() returned error: -4
我假设这是某种内存泄漏,但我在代码中看不出是什么导致了它。好的,结果是套接字的缓冲区无法控制地增长,因为向它提供数据的速度比刷新数据的速度快 我通过检查
BytesWrite
给出的值,只写入这么多字节(实际上,将缓冲区重新填充回64k),解决了这个问题
我的固定代码现在如下所示:
void AsynchronousRetrieveCommand::start()
{
connect(socket(), SIGNAL(bytesWritten(qint64)), this, SLOT(sendNextBlock(qint64)));
sendNextBlock(64*1024);
}
void AsynchronousRetrieveCommand::sendNextBlock(qint64 bytes)
{
socket()->write(file->read(bytes));
}
您正在发送的文件有多大?大约500 MB,但仅传输了5 MB后就会发生错误。但这不重要,因为我正在逐块发送,每个块只有64k。您缺少一些错误处理,最好使用(char*,qint64)重载读/写并检查返回值以确保数据确实读/写过。我假设如果我不能读取文件,那么
QFile::open
首先会失败(我对此进行了检查)读/写((const)char*,qint64)返回读/写的字节数。不检查返回值可能导致数据丢失。此外,打开文件后,读/写仍然可能失败(然后返回-1)。