且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多客户端/服务器tcp应用程序使用qt

更新时间:2023-11-22 17:57:46

在Qt中构建服务器非常简单。你必须导出 QTcpServer 并实现一些方法或插槽。这也适用于客户端。
导出 QTcpSocket ,您将拥有您的客户端。

to build a server in Qt is very simple. you have to derive QTcpServer and implement some methods or slot. This is valid for the clients too. Derive QTcpSocket and you will have your client.

incomingConnection(int socketDescriptor) .so在您的情况下,您可以保存客户端传入地图(地图,因为每个客户端都有自己的id)。

in example, to detect a client incoming you implement virtual void incomingConnection ( int socketDescriptor ) .so in your case you can save clients incoming in a map(a map because every client will have his own id).

在服务器和客户端,你可能想实现 readyRead()插槽。
这个槽做你想要的沟通的东西。

in both server and client you will probably want to implement readyRead() slot. this slot do the communication thing that you want. in fact inside this slot the server can receive and send to client messages and vice-versa.

这是一个简单的 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");
}

就是这样!