一小例子,了解 TCP 通讯流程 | Qt 示例

Hi,我是你们的工具人,老吴。

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

代码链接:

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

运行效果:

Server 端

运行效果:

显示 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() 以实现发送消息的功能。

获取 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 端

运行效果:

每次点击 "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 通讯流程:

图片来源:

https://blog.csdn.net/qq_32298647/article/details/74834254

—— The End ——

推荐阅读:

专辑 | Linux 系统编程

专辑 | Linux 驱动开发

专辑 | 每天一点 C

专辑 | 开源软件

专辑 | Qt 入门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值