QLocalSocket Named pipe
-
Hello all,
I am using QLocalSocket and QLocalServer for named pipe in MainWindows as member variables. QLocalSocket for multiple client put into QVector<QLocalSocket*>, it works great. But I still have problem with disconnection. I am using a slot void disconnect and a MainWindow::closeEvent. Is this code below correct? I need the slot disconnect, if other part close the connection. And CloseEvent is my part to close the connection. I got crash in slot disconnect.
QVector<QLocalSocket*> clients;
void MainWindow::disconnected() { for ( auto& client: this->clients ) { if ( client->state() == QLocalSocket::UnconnectedState ) { client->deleteLater(); } } } void MainWindow::closeEvent( QCloseEvent *event ) { for ( auto& client: this->clients ) { if ( client->isValid() ) { client->disconnectFromServer(); } } event->accept(); }
-
@JonB said in QLocalSocket Named pipe:
@king558
Run it to crash in the debugger, and look at the stack trace to verify precisely which line of your code it dies from. I assume that if you comment out theclient->deleteLater();
it does not crash?Thx for your help
@kshegunov said in QLocalSocket Named pipe:
At a glance, you don't remove the
client
from the list so after disconnecting one client you're left with a dangling pointer.Thx also for your help.
Currently I have a workaround like that. But the design of QLocalSocket slot is bad, if there are not another proper solution available.
this->index = -1;
void MainWindow::disconnected() { if ( this->index >= 0 ) { const auto& client = this->clients[ this->index ]; if ( client->state() == QLocalSocket::UnconnectedState ) { client->deleteLater(); } } else { for ( const auto& client: this->clients ) { if ( client->state() == QLocalSocket::UnconnectedState ) { client->deleteLater(); } } } } void MainWindow::closeEvent( QCloseEvent *event ) { for ( const auto& client = this->clients ) { this->index++; if ( client->isValid() ) { client->disconnectFromServer(); } } event->accept(); }
I watched many times in stack windows. in closeEvent is a loop and in slot disconnect, that means disconnectFromServer would cause slot disconnect have been called. client->deleteLater(); would be called multiple times, each client two times. Why do disconnected not have a parameter, it would indicate which client object has send the signal?
-
@king558 said in QLocalSocket Named pipe:
Why do disconnected not have a parameter, it would indicate which client object has send the signal?
Usually it isn't needed. However there's an easy solution:
void MainWindow::disconnected(QLocalSocket * socket) { // Remove from list and deleteLater() } // Where you create the socket: QLocalSocket * socket; // Init socket etc. QObject::connect(socket, &QLocalSocket::disconnected, mainWindow, std::bind(&MainWindow::disconnected, mainWindow, socket));
-