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 <timur.pocheptsov@qt.io>
Reviewed-by: Konrad Kujawa <konrad.kujawa@qt.io>
This commit is contained in:
Mårten Nordheim 2023-06-15 10:18:11 +02:00
parent 226d06402b
commit 2a80adc2f6
2 changed files with 7 additions and 7 deletions

View File

@ -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);

View File

@ -39,7 +39,7 @@ private:
PeerManager *peerManager;
Server server;
QMultiHash<QByteArray, Connection *> peers;
QHash<QByteArray, Connection *> peers;
};
#endif