快捷搜索:  汽车  科技

qt写tcp通信程序:一小例子了解TCP

qt写tcp通信程序:一小例子了解TCP1、QTcpServer 是对 TCP-based server 的封装。// server.cpp Server::Server(QWidget *parent) : QDialog(parent) statusLabel(new QLabel) { // 建立 TCP Server,并监听 tcpServer = new QTcpServer(this); tcpServer->listen() // 获取 Server 的 IP 地址,并用其初始化 UI [...] // 一旦有 TCP 连接,则调用 sendMsg() 发送数据给客户端 connect(tcpServer &QTcpServer::newConnection this &Server::sendMsg); } 要点:

Hi,今天用一个小例子,陈述一下 Qt 里使用 TCP 通讯的流程。

代码链接:

https://doc.qt.io/qt-5/examples-network.html

运行效果:

qt写tcp通信程序:一小例子了解TCP(1)

Server 端运行效果:

qt写tcp通信程序:一小例子了解TCP(2)

显示 IP 端口,然后静静地的等待客户端的连接。

源码文件:

msg_server/ ├── msg_server.pro ├── main.cpp ├── server.cpp └── server.h

源码分析如下。

创建 TCP Server

在构造函数中进行初始化:

// server.cpp Server::Server(QWidget *parent) : QDialog(parent) statusLabel(new QLabel) { // 建立 TCP Server,并监听 tcpServer = new QTcpServer(this); tcpServer->listen() // 获取 Server 的 IP 地址,并用其初始化 UI [...] // 一旦有 TCP 连接,则调用 sendMsg() 发送数据给客户端 connect(tcpServer &QTcpServer::newConnection this &Server::sendMsg); }

要点:

1、QTcpServer 是对 TCP-based server 的封装。

2、QTcpServer::listen() 用于监听是否有客户端发起连接。

3、一旦有客户端访问,QTcpServer 会发出 newConnection() 信号,我们通过绑定槽函数 sendMsg() 以实现发送消息的功能。

嵌入式物联网需要学的东西真的非常多,千万不要学错了路线和内容,导致工资要不上去!

无偿分享大家一个资料包,差不多150多G。里面学习内容、面经、项目都比较新也比较全!某鱼上买估计至少要好几十。

点击这里找小助理0元领取:嵌入式物联网学习资料(头条)

qt写tcp通信程序:一小例子了解TCP(3)

qt写tcp通信程序:一小例子了解TCP(4)

获取 Server IP

在界面上显示服务端的 IP 信息:

// server.cpp Server::Server(QWidget *parent) : QDialog(parent) statusLabel(new QLabel) { // 创建 TCP Server [...] QString ipAddress; // 获得所有的 IP 地址 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // 解析出第一个可用的 IPv4 地址 for (int i = 0; i < ipAddressesList.size(); i) { if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) { ipAddress = ipAddressesList.at(i).toString(); break; } } // 初始化 UI [...] }

要点:

1、QNetworkInterface 是对网络接口 (例如 lo、eth0...) 的封装。

2、QNetworkInterface::allAddresses() 会返回系统里所有的 IP 地址。

3、QHostAddress 是对 IP 地址(IPv4、IPv6) 的封装。

4、QHostAddress::toIPv4Address() 会将点分式的 IPv4 地址转换为数字式,例如 127.0.0.1 会被转换为 0x7F000001,失败则返回 0。

给客户端发送消息

当有客户端连接到来时,槽函数 sendMsg()会被调用 :

// server.cpp void Server::sendMsg() { // Prepare message QByteArray block; QDataStream out(&block QIODevice::WriteOnly); out << message[QRandomGenerator::global()->bounded(message.size())]; // Get pending connection QTcpsocket *clientConnection = tcpServer->nextPendingConnection(); connect(clientConnection &QAbstractSocket::disconnected clientConnection &QObject::deleteLater); // Send message clientConnection->write(block); clientConnection->disconnectFromHost(); }

要点:

1、QTcpSocket 是对 TCP Socket 的封装。

2、为了与主机无关 (字节序等),这里选用 QByteArray 以二进制的格式来存储数据。使用 QDataStream 可以轻松地将 Message 写到 QByteArray 里。

3、QDataStream 从各种 IO 设备 (QIODeice 的子类),例如 QByteArray、文件 (QFile) 等读写二进制数据。

4、从 QTcpServer::nextPendingConnection() 获得客户端的 Socket。

5、用 QTcpSocket::write() 将 Message 通过网络发给客户端。

6、最后,通过 QTcpSocket::disconnectFromHost 断开连接,它会等待直到数据成功被写出去。

Client 端运行效果:

qt写tcp通信程序:一小例子了解TCP(5)

每次点击 "Get Message" 按钮,客户端都会从服务端随机获取到一条问候信息。

源码文件:

msg_client/ ├── msg_client.pro ├── client.cpp ├── client.h └── main.cpp 创建 TCP Socket

// client.cpp Client::Client(QWidget *parent) : QDialog(parent) hostCombo(new QComboBox) portLineEdit(new QLineEdit) statusLabel(new QLabel(tr("This examples requires that you run the\n Message Server example as well."))) getMsgButton(new QPushButton(tr("Get Message"))) tcpSocket(new QTcpSocket(this)) { // Init UI [...] // Setup QDataStream's source in.setDevice(tcpSocket); in.setVersion(QDataStream::Qt_5_10); // Setup signal & slot connect(getMsgButton &QAbstractButton::clicked this &Client::requestNewMsg); connect(tcpSocket &QIODevice::readyRead this &Client::readMsg); }

要点:

1、用 QTcpSocket 创建 TCP Socket。

2、将 QDataStream 数据流的输入源设置为 Socket。

3、设置信号槽:当 Socket 有数据时,调用 readMsg() 将其读走。

从服务端读取消息

当用户点击 "Get Message" 按钮时,requestNewMsg() 会被调用

// client.cpp void Client::requestNewMsg() { getMsgButton->setEnabled(false); tcpSocket->abort(); tcpSocket->connectToHost(hostCombo->currentText() portLineEdit->text().toInt()); }

要点:

1、QTcpSocket::connectToHost() 向服务端发起连接。

2、该函数没有返回值,是因为当有错误发生时,socket 会发出 error() 信号,我们可以通过绑定对应的槽函数进行错误处理。

3、成功连接后,服务端会随机发送一条信息过来,客户端接收到消息后,readMsg() 会被调用。

// client.cpp void Client::readMsg() { QString ; in >> nextFortune; statusLabel->setText(nextFortune); getMsgButton->setEnabled(true); }

很简单的流操作,读到信息后,将其显示在界面上。

总结

用一张图总结一下 Qt TCP 通讯流程:

qt写tcp通信程序:一小例子了解TCP(6)

原文链接:https://mp.weixin.qq.com/s/aCyV4HBwzTUZbCrdKsLtBw

文章转载自:老吴嵌入式

文章来源于:一小例子,了解 TCP 通讯流程 | Qt 示例

原文链接:一小例子,了解 TCP 通讯流程 | Qt 示例

版权声明:本文来源于网络,免费传达知识,版权归原作者所有,如涉及作品版权问题,请联系我进行删除

猜您喜欢: