Qt 如何从服务器向已连接的客户端发送消息

How to send messages to connected clients from server in Qt

我知道如何在发出 QTcpServer newConnection 时向新连接的客户端发送消息。我做的是这样的:

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

但我想做的是,只要在服务器中单击发送消息按钮,它就会向当前连接的客户端发送消息。我提供的代码只能向新连接的客户端发送一条新消息。我不知道如何实现我想做的事情,所以有人可以为我提供一种方法吗?我是 Qt 网络的新手。

谢谢

只需将您的连接存储在容器中。像这样: 在您的 ServerInterface h 文件中:

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

在您的 ServerInterface cpp 文件中:

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