【QT篇】网络调试助手

一、项目概述

1.功能介绍

•支持开启服务端监听,客户端连接

•支持客户端、服务端收发消息

•支持多客户端连接服务端

2.界面预览

二、常用类 

在此主要罗列一些主要使用的类,具体请查阅QT帮助手册

•QTcpServer
•QTcpSocket
•QNetworkInterface
•QHostAddress
•QMouseEvent
•QTextCharFormat

三、项目源码

https://github.com/GeekerGao/TCP-Client-Server

若Github登陆不上,可私信要网盘链接!

部分代码

server

#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QNetworkInterface>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);

    server = new QTcpServer(this);

    connect(ui->comboBoxChildren,&MyComboBox::on_ComboBox_clicked,this,&Widget::mComboBox_refresh);
    connect(server,SIGNAL(newConnection()),this,SLOT(on_newClient_connect()));
    ui->btnApart->setEnabled(false);
    ui->btnStopListen->setEnabled(false);
    ui->btnSend->setEnabled(false);

    QList<QHostAddress> address = QNetworkInterface::allAddresses();
    for(QHostAddress tmp : address){
        if(tmp.protocol() == QAbstractSocket::IPv4Protocol){
            ui->comboBoxAddr->addItem(tmp.toString());
        }
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_newClient_connect()
{
    if(server->hasPendingConnections()){
        QTcpSocket* connection = server->nextPendingConnection();
        ui->textEditRev->insertPlainText("客户端地址:"+connection->peerAddress().toString()
                                         +"\n客户端端口号:"+QString::number(connection->peerPort())+"\n");
        connect(connection,SIGNAL(readyRead()),this,SLOT(on_readyRead_handler()));
        connect(connection,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                this,SLOT(mstateChanged(QAbstractSocket::SocketState)));
        ui->comboBoxChildren->addItem(QString::number(connection->peerPort()));
        ui->comboBoxChildren->setCurrentText(QString::number(connection->peerPort()));
        if(!ui->btnSend->isEnabled()){
            ui->btnSend->setEnabled(true);
        }
    }
}

void Widget::on_btnListen_clicked()
{
    int port = ui->lineEditPort->text().toInt();
    if(!server->listen(QHostAddress(ui->comboBoxAddr->currentText()),port)){
        QMessageBox msgBox;
        msgBox.setWindowTitle("监听失败");
        msgBox.setText("端口号被占用");
        msgBox.exec();
        return;
    }
    ui->btnListen->setEnabled(false);
    ui->btnApart->setEnabled(true);
    ui->btnStopListen->setEnabled(true);
}

void Widget::on_readyRead_handler()
{
    QTcpSocket *tmpSock = qobject_cast<QTcpSocket *>(sender());
    QByteArray revData = tmpSock->readAll();
    ui->textEditRev->moveCursor(QTextCursor::End);
    ui->textEditRev->ensureCursorVisible();
    ui->textEditRev->insertPlainText("客户端:"+revData+"\n");
}

void Widget::mdisconnected()
{
    QTcpSocket *tmpSock = qobject_cast<QTcpSocket *>(sender());

    ui->textEditRev->insertPlainText("客户端断开!\n");
    tmpSock->deleteLater();
}

void Widget::mstateChanged(QAbstractSocket::SocketState socketState)
{
    int tmpIndex;
    QTcpSocket *tmpSock = qobject_cast<QTcpSocket *>(sender());
    switch(socketState){
    case QAbstractSocket::UnconnectedState:
        ui->textEditRev->insertPlainText("客户端断开!\n");
        tmpIndex = ui->comboBoxChildren->findText(QString::number(tmpSock->peerPort()));
        ui->comboBoxChildren->removeItem(tmpIndex);
        tmpSock->deleteLater();
        if(ui->comboBoxChildren->count() == 0)
            ui->btnSend->setEnabled(false);
        break;
    case QAbstractSocket::ConnectedState:
    case QAbstractSocket::ConnectingState:
        ui->textEditRev->insertPlainText("客户端接入!");
        break;
    }
}

void Widget::mComboBox_refresh()
{
    ui->comboBoxChildren->clear();
    QList<QTcpSocket*> tcpSocketClients = server->findChildren<QTcpSocket*>();
    for(QTcpSocket* tmp : tcpSocketClients){
        if(tmp != nullptr)
            ui->comboBoxChildren->addItem(QString::number(tmp->peerPort()));
    }
    ui->comboBoxChildren->addItem("All");
}

void Widget::on_btnSend_clicked()
{
    QList<QTcpSocket*> tcpSocketClients = server->findChildren<QTcpSocket*>();
    //当用户不选择向所有客户端进行发送时候
    if(tcpSocketClients.isEmpty()){
        QMessageBox msgBox;
        msgBox.setWindowTitle("发送错误!");
        msgBox.setText("当前无连接!");
        msgBox.exec();
        ui->btnSend->setEnabled(false);
        return;
    }
    if(ui->comboBoxChildren->currentText() != "All"){
        QString currentName = ui->comboBoxChildren->currentText();
        for(QTcpSocket* tmp : tcpSocketClients){
            if(QString::number(tmp->peerPort()) == currentName){
                tmp->write(ui->textEditSend->toPlainText().toStdString().c_str());
            }
        }
    }else{
        //遍历所有子客户端,并一一调用write函数,向所有客户端发送消息
        for(QTcpSocket* tmp : tcpSocketClients){
                QByteArray sendData = ui->textEditSend->toPlainText().toUtf8();
                tmp->write(sendData);
        }
    }
}

void Widget::on_btnStopListen_clicked()
{
    QList<QTcpSocket*> tcpSocketClients = server->findChildren<QTcpSocket*>();
    for(QTcpSocket* tmp : tcpSocketClients){
        tmp->close();
    }
    server->close();

    ui->btnListen->setEnabled(true);
    ui->btnApart->setEnabled(false);
    ui->btnStopListen->setEnabled(false);
}

void Widget::on_btnApart_clicked()
{
    on_btnStopListen_clicked();
    delete server;
    this->close();
}

client

#include "widget.h"
#include "ui_widget.h"

#include <QTimer>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);

    ui->btnDisconnected->setEnabled(false);
    ui->btnSend->setEnabled(false);

    client = new QTcpSocket(this);
    connect(client,SIGNAL(readyRead()),this,SLOT(mRead_data_From_Server()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btnConnected_clicked()
{
    client->connectToHost(ui->lineEditIPAddr->text(),ui->lineEditPort->text().toInt());

    timer = new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(5000);

    connect(timer,SIGNAL(timeout()),this,SLOT(onTimeout()));
    connect(client,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(client,SIGNAL(error(QAbstractSocket::SocketError)),
                          this,SLOT(onError(QAbstractSocket::SocketError)));

    this->setEnabled(false);
    timer->start();
}

void Widget::mRead_data_From_Server()
{
    ui->textEditRev->moveCursor(QTextCursor::End);
    ui->textEditRev->ensureCursorVisible();
    mInsertTextByColor(Qt::black,client->readAll());
}

void Widget::on_btnSend_clicked()
{
    QByteArray sendData = ui->textEditSend->toPlainText().toUtf8();
    client->write(sendData);
    mInsertTextByColor(Qt::red,sendData);
}

void Widget::on_btnDisconnected_clicked()
{
    client->disconnectFromHost();
    client->close();
    ui->textEditRev->append("中止连接!");
    ui->btnConnected->setEnabled(true);
    ui->lineEditPort->setEnabled(true);
    ui->lineEditIPAddr->setEnabled(true);
    ui->btnDisconnected->setEnabled(false);
    ui->btnSend->setEnabled(false);
}

void Widget::onConnected()
{
    timer->stop();
    this->setEnabled(true);
    ui->textEditRev->append("连接成功!");
    ui->btnConnected->setEnabled(false);
    ui->lineEditPort->setEnabled(false);
    ui->lineEditIPAddr->setEnabled(false);
    ui->btnDisconnected->setEnabled(true);
    ui->btnSend->setEnabled(true);
}

void Widget::onError(QAbstractSocket::SocketError error)
{
    ui->textEditRev->insertPlainText("连接出问题:"+client->errorString());
    this->setEnabled(true);
    on_btnDisconnected_clicked();
}

void Widget::onTimeout()
{
    ui->textEditRev->insertPlainText("连接超时!");
    client->abort();
    this->setEnabled(true);
}

void Widget::mInsertTextByColor(Qt::GlobalColor color,QString str)
{
    QTextCursor cursor = ui->textEditRev->textCursor();
    QTextCharFormat format;
    format.setForeground(QBrush(QColor(color)));
    cursor.setCharFormat(format);
    cursor.insertText(str);
}
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: QT网络调试助手是一款基于QT平台开发的网络调试工具。它的主要功能是辅助开发人员进行网络调试工作,能够对HTTP、TCP、UDP、WebSocket等协议进行解析和分析,提供可视化的界面展示,便于开发人员快速定位和解决问题。 QT网络调试助手具有以下几个主要特点: 1. 集成多种协议支持:QT网络调试助手支持HTTP、TCP、UDP、WebSocket等多种协议,能够解析协议包,展示数据信息。通过这些数据信息,可以快速定位和解决网络开发中出现的各种问题。 2. 监听端口支持:QT网络调试助手还支持监听指定端口,能够实时获取网络数据流,方便进行数据分析。同时,它还提供了响应数据修改的功能,可以在不影响源数据的情况下,对数据进行调整和修改。 3. 界面友好:QT网络调试助手提供了直观、友好的界面,包含请求列表、响应列表、WebSocket列表等多种显示模式,以及自定义筛选条件,让开发人员可以更加方便地操作和查看数据信息。 4. 精简实用:QT网络调试助手的设计十分精简实用,针对网络调试的核心需求进行了精心设计,避免了繁琐的操作过程和不必要的功能干扰。 总之,QT网络调试助手是一个功能强大、易于操作、界面友好的网络调试工具,可以帮助开发人员快速发现和解决网络开发中出现的各种问题。 ### 回答2: Qt网络调试助手是一款基于Qt框架开发的网络调试工具,它可以帮助开发人员在网络通信过程中对报文进行捕获、分析和调试Qt网络调试助手主要包括以下几个功能: 1. 报文捕获功能:Qt网络调试助手可以捕获网络通信过程中的请求报文和响应报文,并以可视化的方式展示出来。这对于开发人员来说非常重要,因为它可以帮助他们快速找到报文中的问题。 2. 报文分析功能:Qt网络调试助手可以对捕获的报文进行分析,包括解析HTTP协议、分析应用层协议等。开发人员可以通过这个功能更深入地了解网络通信的过程,更快地解决问题。 3. 报文编辑功能:Qt网络调试助手还可以对捕获的报文进行编辑,包括修改请求参数、请求头、响应参数、响应头等。这对于开发人员进行网络调试非常方便。 4. 报文保存功能:Qt网络调试助手还可以将捕获的报文保存到本地文件中,以便于之后的查看和分析。 总体来说,Qt网络调试助手是一款非常实用的网络调试工具,它为开发人员提供了捕获、分析、编辑和保存网络报文的功能,让开发人员更快地找到网络通信中的问题,并解决它们。同时它也是一款开源工具,可以帮助开源社区的发展。 ### 回答3: Qt网络调试助手是一款功能强大的网络调试工具。它能够帮助开发者快速识别和解决网络问题,是一个必备的调试工具。 Qt网络调试助手具有以下主要特点: 1. 支持多个网络协议 Qt网络调试助手支持常见的网络协议,如HTTP/HTTPS、TCP/UDP、WebSocket等。可以轻松地在这些协议之间进行切换,并查看它们的详细信息。 2. 支持数据的查看和编辑 在调试过程中,开发者可以实时查看请求和响应的数据,同时也可以编辑这些数据来模拟各种情况。 3. 支持数据的保存和发送 Qt网络调试助手也支持将数据保存到本地,以便后续分析。同时还可以发送数据到指定的地址,以便测试网络性能和稳定性。 4. 支持用户名和密码的验证 如果需要验证用户名和密码,Qt网络调试助手也可以轻松地完成验证过程。这非常有用,减少了开发人员的负担。 总之,Qt网络调试助手是一款十分实用的网络调试工具。它可以帮助开发人员快速定位和解决网络问题,提高工作效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿gao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值