在 Qt 中构建服务器非常简单。您必须派生QTcpServer并实现一些方法或插槽。这对客户也有效。派生QTcpSocket,您将拥有您的客户端。
例如,要检测客户端传入,您可以实现virtual void incomingConnection ( int socketDescriptor ) 。因此,在您的情况下,您可以将传入的客户端保存在地图中(地图,因为每个客户端都有自己的 id)。
在服务器和客户端中,您可能都希望实现readyRead()插槽。这个插槽做你想要的通信事情。事实上,在这个插槽内,服务器可以接收和发送给客户端消息,反之亦然。
这是一个典型的readyread:
void Client::readyRead() {
while (this->canReadLine()) {
// here you get the message from the server
const QString& line = QString::fromUtf8(this->readLine()).trimmed();
}
}
这是发送消息的方法:
void Client::sendMessage(const QString& message) {
this->write(message.toUtf8());
this->write("\n");
}
就这样!