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

The*_*ang 0 qt qtcpserver

我知道如何在发出消息时向新连接的客户端发送消息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);
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢。

And*_*nov 5

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

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

在您的 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);
  }
}
Run Code Online (Sandbox Code Playgroud)