美文网首页
Qt官方示例-TCP客户端/服务器示例

Qt官方示例-TCP客户端/服务器示例

作者: Qt君 | 来源:发表于2019-12-23 20:31 被阅读0次

该示例演示了在本地主机上的TCP客户端和服务器是如何通讯的。

demo.gif

客户端

  绑定信号槽。

connect(&tcpClient, &QAbstractSocket::connected, this, &Dialog::startTransfer); /* 连接到服务器时回送消息给服务器 */
connect(&tcpClient, &QIODevice::bytesWritten,
        this, &Dialog::updateClientProgress); /* 绑定写数据到服务器的信号槽 */

  连接到服务器。

tcpClient.connectToHost(QHostAddress::LocalHost, tcpServer.serverPort());

  这里比较有意思的是,客户端连接到服务器->客户端(tcpClient)触发startTransfer槽函数->调用tcpClient.write->触发QIODevice::bytesWritten信号->触发updateClientProgress槽函数调用->就一直tcpClient.write,直到if条件不成立后后停止发送。

void Dialog::startTransfer()
{
    // called when the TCP client connected to the loopback server
    bytesToWrite = TotalBytes - int(tcpClient.write(QByteArray(PayloadSize, '@')));
    clientStatusLabel->setText(tr("Connected"));
}
void Dialog::updateClientProgress(qint64 numBytes)
{
    // called when the TCP client has written some bytes
    bytesWritten += int(numBytes);

    // only write more if not finished and when the Qt write buffer is below a certain size.
    if (bytesToWrite > 0 && tcpClient.bytesToWrite() <= 4 * PayloadSize) /* 直到if条件不成立后后停止发送 */
        bytesToWrite -= tcpClient.write(QByteArray(qMin(bytesToWrite, PayloadSize), '@'));

    clientProgressBar->setMaximum(TotalBytes);
    clientProgressBar->setValue(bytesWritten);
    clientStatusLabel->setText(tr("Sent %1MB").arg(bytesWritten / (1024 * 1024)));
}

服务端

  绑定信号槽用于新连接:

connect(&tcpServer, &QTcpServer::newConnection,
        this, &Dialog::acceptConnection);

  监听客户端连接。

!tcpServer.isListening() && !tcpServer.listen()

  服务端新连接到来:

void Dialog::acceptConnection()
{
    tcpServerConnection = tcpServer.nextPendingConnection();
    if (!tcpServerConnection) {
        serverStatusLabel->setText(tr("Error: got invalid pending connection!"));
        return;
    }

    connect(tcpServerConnection, 
            &QIODevice::readyRead,
            this, 
            &Dialog::updateServerProgress); /* 接受客户端数据的槽函数 */
    connect(tcpServerConnection,
            QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),
            this, 
            &Dialog::displayError); /* 错误反馈 */
    connect(tcpServerConnection, 
            &QTcpSocket::disconnected,
            tcpServerConnection, 
            &QTcpSocket::deleteLater); /* 断开反馈 */

    serverStatusLabel->setText(tr("Accepted connection"));
    tcpServer.close(); 
}

  接收来自客户端的数据:

void Dialog::updateServerProgress()
{
    bytesReceived += int(tcpServerConnection->bytesAvailable());
    tcpServerConnection->readAll(); /* 读数据 */

    serverProgressBar->setMaximum(TotalBytes);
    serverProgressBar->setValue(bytesReceived); /* 设置进度条 */
    serverStatusLabel->setText(tr("Received %1MB") /* 显示在界面上 */
                               .arg(bytesReceived / (1024 * 1024)));

    if (bytesReceived == TotalBytes) {
        tcpServerConnection->close();
        startButton->setEnabled(true);
#ifndef QT_NO_CURSOR
        QApplication::restoreOverrideCursor();
#endif
    }
}

关于更多

  • QtCreator软件可以找到:
what_find.png
  • 或在以下Qt安装目录找到:
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\network\loopback
  • 相关链接
https://doc.qt.io/qt-5/qtnetwork-loopback-example.html
  • Qt君公众号回复『Qt示例』获取更多内容。

相关文章

  • Qt官方示例-TCP客户端/服务器示例

    该示例演示了在本地主机上的TCP客户端和服务器是如何通讯的。 客户端   绑定信号槽。   连接到服务器。   这...

  • 0002-TcpListener/TcpClient异步编程

    服务器代码示例: 客户端代码示例:

  • Socket之TCP相关

    客户端socket简单示例(以下都是针对TCP协议) 服务端sockt简单示例 客户端流程 客户端创建socket...

  • day19-网络通信

    1.socket服务器 代码示例 2.socket客户端 代码示例 3.socket服务器升级 代码示例 4.接受...

  • Qt官方示例-窗口标志

    窗口标志示例展示了如何使用Qt中可用的窗口标志类型来指定窗口系统属性。   根据示例整理出来的各窗口标志作用一览表...

  • Qt官方示例-数字时钟

    基于QLCDNumber实现的LCD的时钟显示。   DigitalClock继承于QLCDNumber,并实现一...

  • Qt官方示例-目录视图

    该示例显示了本地文件系统的树状视图。它使用QFileSystemModel类提供文件和目录信息。   声明mode...

  • Golang高并发教程之 TCP时钟服务器

    示例:TCP时钟服务器 之后使用nc(netcat)连接tcp服务器 返回结果 分析 服务器分析 net.List...

  • 0001-TcpListener/TcpClient同步编程

    在使用TcpListener/TcpClient同步编程之前,要引入两个命名空间 服务器代码示例: 客户端代码示例:

  • Qt官方示例-计算器

    该示例显示了如何使用信号和槽来实现计算器小部件的功能,以及如何使用QGridLayout将子小部件放置在网格中。 ...

网友评论

      本文标题:Qt官方示例-TCP客户端/服务器示例

      本文链接:https://www.haomeiwen.com/subject/dpetoctx.html