From 2a80adc2f683a6809d0ce30c2423911f32304de2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Thu, 15 Jun 2023 10:18:11 +0200 Subject: [PATCH] Network-chat example: Use QHash for peers We don't key it on IP address anymore so we can drop the use of QMultiHash. This also requires moving the connections for error and disconnected to readyForUse so we don't remove an active connection when a second connection attempt happens from the same peer process. But since we still need to deallocate those connection attempts if they error out or simply disconnect, we connect their signals to the QObject::deleteLater slot. In some cases we might call deleteLater twice but that's fine. Change-Id: I48c27de1e51a52ef61cfb941a7a81b358ae9ce3f Reviewed-by: Timur Pocheptsov Reviewed-by: Konrad Kujawa --- examples/network/network-chat/client.cpp | 12 ++++++------ examples/network/network-chat/client.h | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/network/network-chat/client.cpp b/examples/network/network-chat/client.cpp index 495ae90d023..c637224127e 100644 --- a/examples/network/network-chat/client.cpp +++ b/examples/network/network-chat/client.cpp @@ -45,10 +45,9 @@ bool Client::hasConnection(const QByteArray &peerUniqueId) const void Client::newConnection(Connection *connection) { connection->setGreetingMessage(peerManager->userName(), peerManager->uniqueId()); - - connect(connection, &Connection::errorOccurred, this, &Client::connectionError); - connect(connection, &Connection::disconnected, this, &Client::disconnected); connect(connection, &Connection::readyForUse, this, &Client::readyForUse); + connect(connection, &Connection::errorOccurred, connection, &QObject::deleteLater); + connect(connection, &Connection::disconnected, connection, &QObject::deleteLater); } void Client::readyForUse() @@ -62,8 +61,9 @@ void Client::readyForUse() return; } - connect(connection, &Connection::newMessage, - this, &Client::newMessage); + connect(connection, &Connection::errorOccurred, this, &Client::connectionError); + connect(connection, &Connection::disconnected, this, &Client::disconnected); + connect(connection, &Connection::newMessage, this, &Client::newMessage); peers.insert(connection->uniqueId(), connection); QString nick = connection->name(); @@ -85,7 +85,7 @@ void Client::connectionError(QAbstractSocket::SocketError /* socketError */) void Client::removeConnection(Connection *connection) { - if (peers.remove(connection->uniqueId(), connection) > 0) { + if (peers.remove(connection->uniqueId())) { QString nick = connection->name(); if (!nick.isEmpty()) emit participantLeft(nick); diff --git a/examples/network/network-chat/client.h b/examples/network/network-chat/client.h index 2ce6afe8269..a09d0c21f66 100644 --- a/examples/network/network-chat/client.h +++ b/examples/network/network-chat/client.h @@ -39,7 +39,7 @@ private: PeerManager *peerManager; Server server; - QMultiHash peers; + QHash peers; }; #endif