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

时间:2018-01-13 14:57:06

标签: 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);
}

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

感谢。

1 个答案:

答案 0 :(得分:4)

只需将您的连接存储在容器中即可。像这样: 在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);
  }
}