多客户端/服务器tcp应用程序使用qt [英] Multi-client / server tcp application using qt

查看:278
本文介绍了多客户端/服务器tcp应用程序使用qt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要在主应用程序和多个服务对象之间进行tcp通信的项目。
(项目是在c + +,我也使用qt)

i am working on a project that requires tcp communication between a "master" application and a number of "servants". (the project is in c++ and i am also using qt)

servants将做一些处理,并将结果发送到master。
到目前为止,它是一个简单的多客户端 - 服务器应用程序。

The "servants" will do some processing and send their results to the "master". So far it's a straightforward multi client-server app.

事情是随机的,主人将要求一些额外的信息,甚至发送他们的信息来改变他们处理的方式。

The thing is that at random times, the master will request some extra info from the servants, and even send them info to change the way they process.

如果我的项目在财富客户端/服务器的例子,我将能够发送消息到服务员大师? (任何想法如何?)

if i base my project on the fortune client/server examples, will i be able to send messages to the servants from the master? (any ideas on how?)

或者我需要将我的工作基于其他的东西(比如聊天客户端吗?)

or do i need to base my work on something else (like the chat client maybe?)?

欢迎任何关于tcp客户端/服务器通信的建议,但是由于我已经使用qt,我不想添加其他库....

any other suggestions on tcp client/server communication are welcome, but since i already use qt, i would prefer not to add other libs....

提前谢谢!

推荐答案

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

就是这样!

这篇关于多客户端/服务器tcp应用程序使用qt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆