The official Qt example -TCP client / server example

This example demonstrates on the local host TCP client and server how is communication.

demo.gif

Client

  Binding signal slot.

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

  Connect to the server.

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

  Here more interesting is that the client connects to the server -> client (tcpClient) trigger startTransfer slot function -> call tcpClient.write-> Trigger QIODevice::bytesWrittenSignal -> trigger updateClientProgress slot function call -> has been tcpClient.write, until after the if condition is not satisfied to stop sending.

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

Server

  Binding signal slot for the new connection:

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

  Listen for client connections.

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

  The new server is connected arrival:

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(); 
}

  Receive data from the client:

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
    }
}

For more

  • In QtCreator software can be found:

what_find.png

  • Or in the Qt installation directory to find:
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\network\loopback
  • Related Links
https://doc.qt.io/qt-5/qtnetwork-loopback-example.html
  • No public Qt Jun reply " Qt example " for more content.
Published 354 original articles · won praise 80 · Views 150,000 +

Guess you like

Origin blog.csdn.net/nicai_xiaoqinxi/article/details/103622465