前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Qt官方示例-TCP客户端/服务器示例

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

作者头像
Qt君
发布2019-12-25 11:16:21
2.9K0
发布2019-12-25 11:16:21
举报
文章被收录于专栏:跟Qt君学编程

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

客户端

  绑定信号槽。

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

  连接到服务器。

代码语言:javascript
复制
tcpClient.connectToHost(QHostAddress::LocalHost, tcpServer.serverPort());

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

代码语言:javascript
复制
void Dialog::startTransfer()
{
    // called when the TCP client connected to the loopback server
    bytesToWrite = TotalBytes - int(tcpClient.write(QByteArray(PayloadSize, '@')));
    clientStatusLabel->setText(tr("Connected"));
}
代码语言:javascript
复制
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)));
}

服务端

  绑定信号槽用于新连接:

代码语言:javascript
复制
connect(&tcpServer, &QTcpServer::newConnection,
        this, &Dialog::acceptConnection);

  监听客户端连接。

代码语言:javascript
复制
!tcpServer.isListening() && !tcpServer.listen()

  服务端新连接到来:

代码语言:javascript
复制
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();
}

  接收来自客户端的数据:

代码语言:javascript
复制
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软件可以找到:
  • 或在以下Qt安装目录找到:
代码语言:javascript
复制
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\network\loopback
  • 相关链接
代码语言:javascript
复制
https://doc.qt.io/qt-5/qtnetwork-loopback-example.html
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-12-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Qt君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 客户端
  • 服务端
  • 关于更多
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档