How can i clear QLocalSocket?

房东的猫 提交于 2019-12-12 04:21:46

问题


I've a problem in clearing the QLocalSocket.

Now I'm sending & receiving the image data through QLocalServer/QLocalSocket.

But in receiving program, memory increases heavily because of piled image data in memory.

so, I want to clean up the socket when the data was read.

but it seems there is no function in QLocalSocket reference.

How can I clear the socket?


回答1:


It looks like the only way to avoid this behaviour is to close socket (not named pipe server) and to open it again once you have received enough data. Also please note, that just closing socket and using the same instance (i.e socket created on stack) caused me a lot of troubles.

I am doing this next way:

On the sender side you have:

dataSocket->write((char*)data, sizeof(data));
dataSocket->disconnectFromServer();

and on the client side:

void LocalSocketClient::requestNewFrame()
{
    if (socket) {
        socket->disconnect();
        socket->deleteLater();
    }

    socket = new QLocalSocket();
    dataStream.setDevice(socket);

    connect(socket, &QLocalSocket::disconnected, this, &LocalSocketClient::requestNewFrame);
    connect(socket, &QLocalSocket::readyRead, this, &LocalSocketClient::readSocket);

    socket->connectToServer(NAMED_PIPE_NAME, QIODevice::ReadOnly);
}

void LocalSocketClient::readSocket()
{
    if(dataStream.readRawData((char*)&currentFrame, sizeof(currentFrame)) > 0) {

    }
}

where currentFrame is predefined known struct of your data.

This is not the most elegant solution as for me, I am still investigating how to avoid infinite new/deleteLater operations. But without them I was getting random writing errors on the sender side (looks like Qt event loop was deleting socket handle once it was closed and not deleted messing up private data of the socket)



来源:https://stackoverflow.com/questions/41053457/how-can-i-clear-qlocalsocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!