TCP/UDP与网络调试助手通信

1.UDP通信

复制代码
    //UDP
    {
        Parameterflag=1;

        this->udpSocket=new QUdpSocket(this);
        bool ok = udpSocket->bind(QHostAddress::Any, 8088); // 绑定到所有可用的网络接口上的12345端口
        if (!ok) {
            // 处理绑定失败的情况
            qDebug()<<"bind err";
        }
        connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);


        this->timer=new QTimer(this);
        connect(timer, &QTimer::timeout, this, &MainWindow::sendDatagram);
        timer->start(1000);

    }

相对应的信号与槽函数连接,使用定时器进行不同时连接;

复制代码
//UDP  发送连接对应地址和端口号

void MainWindow::sendDatagram()
{
    Parameterflag=1;
    QByteArray datagram = "Hello, UDP!";
    QHostAddress receiver("192.168.52.1"); // 目标地址
    quint16 receiverPort = 9999; // 目标端口

    udpSocket->writeDatagram(datagram, receiver, receiverPort);
    qDebug() << "Sent datagram:" << datagram << "to" << receiver.toString() << ":" << receiverPort;
}

接收信息打印连接槽函数

cpp 复制代码
void MainWindow::readPendingDatagrams()
{
    Parameterflag=1;
    //    qDebug() <<"qerrttip";
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(int(udpSocket->pendingDatagramSize()));
        QHostAddress sender;
        quint16 senderPort;

        //        data:接收到发送端的 功能码。
        //        maxSize:功能码长度
        //        sender(可选):发送方的IP地址。
        //        senderPort(可选):发送方的端口号。
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        qDebug() << "Received datagram:" << datagram << "from" << sender.toString() << ":" << senderPort;
    }
}

2. TCP服务器端连接

cpp 复制代码
    //TCP服务器
    //    {
    //        tcpServer=new QTcpServer(this);
    //        connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
    //        if (!tcpServer->listen(QHostAddress::Any, 8088)) {
    //            qDebug() << "Server could not start!";
    //        } else {
    //            qDebug() << "Server started on port 8088!";
    //        }

    //    }

创建对象成功,与其收发信息对应函数

cpp 复制代码
//TCP SERVER
void MainWindow::onNewConnection()
{
    Parameterflag=2;
    //监听一个或多个端口
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead_server);
    connect(clientSocket, &QTcpSocket::disconnected, clientSocket, &QTcpSocket::deleteLater);
}

void MainWindow::onReadyRead_server()
{
    Parameterflag=2;
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    qDebug() << "Received from client:" << data;

    // Echo the data back to the client
    QString response = "Echo: " + QString::fromUtf8(data);
    clientSocket->write(response.toUtf8());
}

3. TCP 客户端连接服务器端

cpp 复制代码
    //TCP客户端
    {
//        Parameterflag=3;
//                this->tcpSocket=new QTcpSocket(this);
//                connect(tcpSocket, &QTcpSocket::connected, this, &MainWindow::onConnected);
//                connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead);

//                // Try to connect to the server
//                tcpSocket->connectToHost("192.168.52.1", 8088);

//                // Optionally, set a timeout for the connection attempt
//                QTimer::singleShot(500, this, &MainWindow::onConnectionTimeout);


    }

连接对应收发信息函数

cpp 复制代码
void MainWindow::onConnected()
{
    Parameterflag=3;
    qDebug() << "Connected to server!";
    // Send some data to the server
    QByteArray data = "Hello, server!";
    tcpSocket->write(data);
}

void MainWindow::onReadyRead()
{
    Parameterflag=3;
    QByteArray data = tcpSocket->readAll();
    qDebug() << "Received from server:" << data;

    // Optionally, close the connection after receiving a response
    // tcpSocket->close();
    // QCoreApplication::quit(); // If you want to quit the application after receiving the response
}

void MainWindow::onConnectionTimeout()
{
    Parameterflag=3;
    if (!tcpSocket->state() == QAbstractSocket::ConnectedState) {
        qDebug() << "Connection timed out!";
        tcpSocket->deleteLater();
        QCoreApplication::quit(); // Or handle the timeout as needed
    }
}

4.在QT中使用下拉框进行对应TCP客户端与服务器端,UDP切换连接

cpp 复制代码
//下拉框发生切换槽函数
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
//    QMessageBox::warning(this, "网络模式", "是否切换通信方式?");
    if(index==0)
    {
        qDebug()<<"UDP";
        //        Parameterflag=1;
        UDPSocketFunction(8088);

    }else if(index==1)
    {
        qDebug()<<"TCP Server";
        //        Parameterflag=2;
        TCPserverFunction(8088);

    }else if(index==2)
    {
        qDebug()<<"TCP Client";
        //        Parameterflag=3;
        TCPClietnFunction(8088);
    }

}

切换不同的通信协议对应将其连接的信号断开,将对象置空,创建对应通信模式连接

(1)UDP 切换函数

cpp 复制代码
void MainWindow::UDPSocketFunction(int udpportnumber)
{
    if(Parameterflag==2)
    {
        QTcpServer *tcpServer = this->tcpServer; // 之前创建的QTcpServer指针
        if (tcpServer) {
            // 停止监听新的连接
            tcpServer->close();
            // 断开信号和槽连接
            disconnect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);

            // 释放并删除tcpServer对象(通过new分配的)
            tcpServer->deleteLater();
            this->tcpServer = nullptr; // 将指针设置为nullptr,以避免悬挂指针

        }
    }else if(Parameterflag==3)
    {
        if (this->tcpSocket->state() == QAbstractSocket::ConnectedState) {
//            QMessageBox::warning(this, "网络模式", "是否切换通信方式?");
            tcpSocket->deleteLater(); // Clean up TCP socket
            tcpSocket = nullptr; // Set pointer to nullptr to avoid dangling pointer
        }
    }


    // UDP相关代码
    {
        QUdpSocket *udpSocket = new QUdpSocket(this); // 创建QUdpSocket对象
        // 绑定到所有可用的网络接口上的指定端口
        bool ok = udpSocket->bind(QHostAddress::Any, udpportnumber);
        if (!ok) {
            // 处理绑定失败的情况
            qDebug()<<"bind err";
            // 处理绑定失败的情况(删除udpSocket对象)
            udpSocket->deleteLater();
        }else{
            connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
            this->udpSocket = udpSocket;

            this->timer=new QTimer(this);
            connect(timer, &QTimer::timeout, this, &MainWindow::sendDatagram);
            timer->start(1000);

        }


    }
}

(2)TCP 服务器切换函数

cpp 复制代码
void MainWindow::TCPserverFunction(int portnumber)
{
    if (this->timer->isActive()) this->timer->stop();
    qDebug()<<"Parameterflag"<<Parameterflag;
    if(Parameterflag==1)
    {
        // UDP相关代码(之前已经存在)
        QUdpSocket *udpSocket = this->udpSocket; // 之前创建的QUdpSocket指针
        if (udpSocket) {
            // 断开信号和槽连接
            disconnect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
            // 其他可能的清理工作...

            // 删除udpSocket对象(如果它是通过new分配的)
            udpSocket->deleteLater();
            this->udpSocket = nullptr; // 将指针设置为nullptr,以避免悬挂指针
        }
    }else if(Parameterflag==3)
    {
        if (this->tcpSocket->state() == QAbstractSocket::ConnectedState) {
//            QMessageBox::warning(this, "网络模式", "是否切换通信方式?");
            tcpSocket->disconnectFromHost(); // Clean up TCP socket
            tcpSocket = nullptr; // Set pointer to nullptr to avoid dangling pointer
        }
    }

    // TCP相关代码
    QTcpServer *tcpServer = new QTcpServer(this); // 创建QTcpSocket对象
    connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
    if (!tcpServer->listen(QHostAddress::Any, portnumber)) {
        qDebug() << "Server could not start!";
    } else {
        qDebug() << "Server started on port portnumber!";
        this->tcpServer = tcpServer;
    }

}

(3)TCP 客户端切换函数

cpp 复制代码
void MainWindow::TCPClietnFunction(int tcpClietnportnumber)
{
    if (this->timer->isActive()) this->timer->stop();
    if(Parameterflag==1)
    {
        // UDP相关代码(之前已经存在)
        QUdpSocket *udpSocket = this->udpSocket; // 之前创建的QUdpSocket指针
        if (udpSocket) {
            // 断开信号和槽连接
            disconnect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
            // 其他可能的清理工作...

            // 删除udpSocket对象(如果它是通过new分配的)
            udpSocket->deleteLater();
            this->udpSocket = nullptr; // 将指针设置为nullptr,以避免悬挂指针
        }
    }else if(Parameterflag==2)
    {
        QTcpServer *tcpServer = this->tcpServer; // 之前创建的QTcpServer指针
        if (tcpServer) {
            // 停止监听新的连接
            tcpServer->close();
            // 断开信号和槽连接
            disconnect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
            // 释放并删除tcpServer对象(通过new分配的)
            tcpServer->deleteLater();
            this->tcpServer = nullptr; // 将指针设置为nullptr,以避免悬挂指针

        }
    }

    //TCP Clietn
    QTcpSocket *tcpSocket=new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::connected, this, &MainWindow::onConnected);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead);

    // Try to connect to the server
    tcpSocket->connectToHost("192.168.52.1", tcpClietnportnumber);

    // Optionally, set a timeout for the connection attempt
    QTimer::singleShot(500, this, &MainWindow::onConnectionTimeout);

    this->tcpSocket=tcpSocket;



}
相关推荐
春风解人意6 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
云絮.7 小时前
网络原理---- 网络层,数据链路层,应用层
网络
Johny_Zhao9 小时前
网络安全等级保护测评实施方案
linux·网络·人工智能·网络安全·信息安全·云计算·等保测评·系统运维·itsm
虹科网络安全10 小时前
使用艾体宝 IOTA 10 CORE+ 监控企业网络中的 AI 流量
网络·人工智能
醉颜凉10 小时前
网络安全必学:粘性MAC地址(Sticky MAC)原理与应用全解析
运维·服务器·网络·安全·web安全
晊晌_h11 小时前
嵌入式从0到精通——Linux C|TCP 并发服务器实现方案详解
服务器·开发语言·tcp/ip
广州灵眸科技有限公司12 小时前
从手动三步到上电即连:4G模组systemd开机自连方案
linux·运维·服务器·开发语言·网络·人工智能·php
埃科光电12 小时前
16K万兆网口彩色线阵相机:四倍带宽 高速真彩检测新方案
网络·图像处理·数码相机·计算机视觉·制造·相机
运维全栈笔记13 小时前
Windows 安装 WSL2 并运行 Ubuntu 24.04 指南
linux·网络·windows·ubuntu
qq_4523962314 小时前
第十篇:《eBPF 可观测性:零侵扰的深度内核追踪》
服务器·网络·php