Search code examples
qtqtcpserver

How to send messages to connected clients from server in Qt


I know that how to send messages to the newly connected client whenever the QTcpServer newConnection is emitted. What I did is like this:

connect(serverConnection.tcpServer, &QTcpServer::newConnection, this, &ServerInterface::sendMessages);

void ServerInterface::sendMessages()
{
    QByteArray messagesToClients;
    QDataStream out(&messagesToClients, QIODevice::WriteOnly);
    QTcpSocket *clientConnection = serverConnection.tcpServer->nextPendingConnection();
    out << inputBox->toPlainText(); //get text from QTextEdit
    clientConnection->write(messagesToClients);
}

But what I want to do is whenever the send messages button is clicked in the server, it will send messages to currently connected clients. The code I provide can only send only one new message to the newly connected client. I have no idea of how to achieve what I want to do, so can someone provide me a way to do that? I am kind of new to Qt networking.

Thanks.


Solution

  • Just store your connections in container. Like this: in your ServerInterface h-file:

    class ServerInterface {
    // your stuff
    public slots:
      void onClientConnected();
      void onClientDisconnected();
    private:
      QVector<QTcpSocket *> mClients;
    };
    

    in your ServerInterface cpp-file :

      connect(serverConnection.tcpServer, SIGNAL(newConnection(), this, SLOT(onClientConnected());
    void ServerInterface::onClientConnected() {
      auto newClient = serverConnection.tcpServer->nextPendingConnection();
      mClients->push_back( newClient );
      connect(newClient, SIGNAL(disconnected()), this, SLOT(onClientDisconnected());
    }
    
    void ServerInterface::onClientDisconnected() {
      if(auto client = dynamic_cast<QTcpSocket *>(sender()) {
       mClients->removeAll(client);
      }
    void ServerInterface::sendMessages() {
      out << inputBox->toPlainText();
      for(auto &client : mClients) {
        client->write(messagesToClients);
      }
    }