Qt practice record: TCP network debugging assistant

Since the project requires the use of network debugging and testing, in order to practice hand, use Qt to write a serial debugging assistant. This article describes a simple press development process, and also relates to a module used in the code section. Detailed code reference source repository.

In terms of code reuse, I believe that Qt is better than MFC, such as the main window code can be used directly, of course, but also to modify the project file name and the corresponding dependencies, interface controls have to re-design and implementation. This is also the default file directly I like Qt Creator created class reasons. In addition, if you use code to achieve pure form layout, with its complex degree even better than using Qt Creator. In fact, the works of this paper is the previous article " Qt practice record: serial debugging assistant " to modify the source code obtained on the basis of. The basic form is provided, icons, status bar, hexadecimal display, the timing of transmission codes, etc., followed directly. Thus, according to the module previously described will not be repeated.

Tool Properties

Features

  • TCP client and server.
  • Hex sending and receiving.
  • Timestamp display
  • For the convenience of testing, this tool has both server and client capabilities that enable spontaneous self-closing. Also it is used alone.

Known Bug

Connection, disconnection and other processing logic is not perfect.
For the server, in theory, should be based on different client needs to send data (or orientation, or all), the current version is not implemented, only to take the last client.

Qt knowledge

  • MainWindow design.
  • Qt TCP programming.
  • Common controls: buttons, check boxes, text edit box controls for the map. Applications logo.
  • button font.
  • Text color of the text edit box to customize the display.

Run 1 shows the results:
Here Insert Picture Description
Figure 1

development process

Project-related

Qt a corresponding dependency network library network, the library needs to be added in the corresponding project file, as follows:

QT       += core gui network

TCP programming

Header files and related variables

#include <QTcpServer>
#include <QTcpSocket>

    QTcpServer *m_tcpServer;

    QList<QTcpSocket*> m_clientList;
    QTcpSocket *m_tcpCliSocket;

Which, m_tcpServer for TCP server, m_tcpCliSocket used to save client connections. m_tcpCliSocket for client connections.

Server

创建服务端:
// server
m_tcpServer = new QTcpServer();

// 连接newConnection信号,svr_newConnect中处理客户端的连接
connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(svr_newConnect()));

监听端口:
m_tcpServer->listen(QHostAddress::Any, port);

关闭:
m_tcpServer->close();

接收数据:
tcpSocket->readAll();

发送数据:
tcpSocket->write(sendData, sendData.size());

When a new client connection will automatically call svr_newConnectthe function, the function saves the client socket, and a received signal and associated data channel:

void MainWindow::svr_newConnect()
{
    printDebugInfo("get new connect");
    QTcpSocket *tcpSocket = m_tcpServer->nextPendingConnection();//新的客户端发起的连接
    QHostAddress clientIp = tcpSocket->peerAddress();//客户端的IP
    quint16 port = tcpSocket->peerPort();//客户端的端口
    if(m_clientList.contains(tcpSocket))
    {
        printDebugInfo(QString("%1:%2 already connected").arg(clientIp.toString()).arg(port));
    }
    else
    {
        printDebugInfo(QString("new connect from %1:%2").arg(clientIp.toString()).arg(port));
        m_clientList.append(tcpSocket);//记录下客户端发起的连接
        connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(svr_disconnect()));
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readyRead())); // 数据接收
    }
}

When the client sends data, automatically it triggers readyReadfunction, which reads the data and show:

void MainWindow::readyRead()
{
    QTcpSocket *tcpSocket = static_cast<QTcpSocket *>(QObject::sender());
    QByteArray buffer = tcpSocket->readAll();
    showRecvData("SERVER> ", buffer);
}

Client

Server IP and port, as follows from the input interface, the server connection function:

QHostAddress serverIp;
serverIp.setAddress(ui->cbRemoteIP->currentText());
uint16_t port=ui->cbRemotePort->currentText().toUShort();
m_tcpCliSocket->connectToHost(serverIp, port);

Note that none isOpenor isValidto determine whether the connection is successful, the need to use waitForConnectedis determined, for example:

if (!m_tcpCliSocket->waitForConnected(600))
{
    printDebugInfo("connect failed");
    return;
}

Client-related signals and slots:

// client
m_tcpCliSocket = new QTcpSocket();
connect(m_tcpCliSocket, SIGNAL(connected()), this, SLOT(cli_connected())); // 客户端连接
connect(m_tcpCliSocket, SIGNAL(disconnected()), this, SLOT(cli_disconnected())); // 客户端断开连接
connect(m_tcpCliSocket, SIGNAL(readyRead()), this, SLOT(cli_receiveData())); // 客户端接收数据

When the remote server sends data to the client, it will automatically trigger cli_receiveDatafunctions:

void MainWindow::cli_receiveData()
{
    QByteArray buffer;
    buffer = m_tcpCliSocket->readAll();
    showRecvData("CLIENT> ", buffer);
}

Interface logic

interface design

Interface uses designers to design, shown in Figure 2. Most of the functionality and interface as the previous article, it is no longer involved.
Here Insert Picture Description
figure 2

Text Color

The project receiving the text displayed There are three types: timestamp + cue, the server data, client data, in order to distinguish, using different colors. The core code is as follows:

    if (m_showTimestamp)
    {
        QDateTime dateTime(QDateTime::currentDateTime());
        timeStr = "[" + dateTime.toString("yyyy-MM-dd HH:mm:ss.zzz") + "] ";
    }

    if (m_recvHex == 1)
    {
        info = buffer.toHex(' ').data();
    }
    else
    {
        info = QString(buffer);
    }

    // 根据类型,使用不同颜色显示
    if (tips.contains("SERVER"))
    {
        info = "<font color=\"blue\">" + info + "</font>";
    }
    else
    {
        info = "<font color=\"green\">" + info + "</font>";
    }

    ui->txtRecv->appendHtml("<font color=\"gray\">" + timeStr + tips + "</font>");
    ui->txtRecv->appendHtml(info);

The use QPlainTextEdit appendHtml function, can specify a color using html format. In this project, prompt gray, the server receives data in blue, the client receives the data in green.

other

The author of this tool basis to achieve custom binary protocol and operating ESP8266, comprising indicating LED lights, relays, factory recovery, the FOTA upgrade firmware verification function test operating mode and other operations, while integrating the foregoing serial function, achieve a full functional testing tool. Since this article is not associated with, not to be reopened. Screenshots show only:
Here Insert Picture Description

Code repository

This works all the source code can be freely used autonomously, including, but not limited to, add, delete, modify, commercial, personal use. The resulting outcomes / consequences almost nothing to do with the author. Limited to the level of ability, this program without any quality assurance, the author of the program no obligation to provide the service.

Warehouse address here .

Published 481 original articles · won praise 244 · Views 1.1 million +

Guess you like

Origin blog.csdn.net/subfate/article/details/104115166