QTcpSocket内存泄漏 [英] QTcpSocket memory leaking

查看:1703
本文介绍了QTcpSocket内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用QTcpServer和QTcpSockets的客户端 - 服务器应用程序设置,似乎有一些巨大的内存泄漏。我想知道如果问题是在我使用Qt的套接字,因为我刚刚设置了一个简单的测试应用程序,并发送250,000,000条消息在循环中,我的客户端上升到75兆。看来如果我有几百万条消息,我看到在我的客户端使用300+ MB的内存。

I have a client-server application setup using QTcpServer and QTcpSockets and seem to have some huge memory leaks. I'm wondering if the problem is in my use of Qt's sockets because I have just set up a simple test application and after sending 250,000,000 messages in a loop my client rises up to 75 meg. It seems that if I have several million messages, I see 300+ MB of memory used in my client.

这似乎不对我,因为我继续发送

This doesn't seem right to me, as I keep sending messages the memory just keeps on rising!

因此,我应该期望我的应用程序在内存中不断上升,因为连接的套接字上有以下代码。如果这个套接字保持开放,我会很快耗尽内存。我错过了什么?

So should I expect my app to constantly rise in memory given the following code on a connected socket. If this socket is left open I'm going to quickly run out of memory. Am I missing something?

if (socket && socket->isOpen())
{
    for(int i = 0; i < 25000000; ++i) {
        QString str = "test";
        socket->write(str.toStdString().c_str());
    }
}


推荐答案

socket是一个内部缓冲的 QIODevice ,无论你写的是什么,它都被缓冲,直到网络栈实际上可以发送出去。你看到的是预期的行为。 write()不是阻止操作,无论如何你应该从未做过 ,除非你认为用户真的很喜欢死了用户界面的应用程序。

The socket is an internally buffered QIODevice, and whatever you've written to it gets buffered until the network stack can actually send it out. What you see is expected behavior. The write() is not a blocking operation, and anyway you should never ever do blocking operations in your GUI thread, unless you think users really enjoy applications with dead user interface.

也许你想把你的写作在一个插槽,获知套接字的进度?套接字都是 QIODevice 。看看有用的信号, bytesWritten()例如。通常推迟写入,除非 bytesToWrite()返回的值低于设置的阈值。您的写字槽可以这样开始:

Perhaps you want to put your writing in a slot that gets informed of the socket's progress? The sockets are all QIODevice. Look there for the useful signals, bytesWritten() for example. It's customary to defer writing unless the value returned by bytesToWrite() is below a set threshold. Your writing slot could begin like so:

// more than 2 pages worth of stuff still to send, we abstain
if (socket->bytesToWrite() > 1<<13) return; 

Nitpick: toStdString() 。。您应该使用:

Nitpick: The toStdString() is completely grauituous. You should be using:

socket->write(str.toUtf8().constData());

不要忘记,对于这种测试,你可以简单地创建一个字节数组而不使用字符串:

Never mind that for such testing, you can trivially create an array of bytes without using a string at all:

const QByteArray testData(1000, ' '); // a 1000 spaces
for (int i = 0; i < 100000; ++i) socket->write(testData);

这篇关于QTcpSocket内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆