Time for action – reacting on a new pending connection
As soon as a client tries to connect to the server, the newConnection()
slot will be called:
void TcpServer::newConnection() { while (m_server->hasPendingConnections()) { QTcpSocket *con = m_server->nextPendingConnection(); m_clients << con; ui->disconnectClients->setEnabled(true); connect(con, SIGNAL(disconnected()), this, SLOT(removeConnection())); connect(con, SIGNAL(readyRead()), this, SLOT(newMessage())); ui->log->insertPlainText( QString("* New connection: %1, port %2\n") .arg(con->peerAddress().toString()) .arg(QString::number(con->peerPort()))); } }
What just happened?
Since more than one connection may be pending, we use hasPendingConnections()
to determine whether there is at least one more pending connection. Each one is then handled inside the while
loop. To get a pending connection of the QTcpSocket
type, we call nextPendingConnection...