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 ...

Get Game Programming Using Qt now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.