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;



}
相关推荐
ZZZCY20031 小时前
华为ENSP--IP编址及静态路由配置
网络·华为
EasyCVR1 小时前
私有化部署视频平台EasyCVR宇视设备视频平台如何构建视频联网平台及升级视频转码业务?
大数据·网络·音视频·h.265
hgdlip2 小时前
主IP地址与从IP地址:深入解析与应用探讨
网络·网络协议·tcp/ip
珹洺2 小时前
C语言数据结构——详细讲解 双链表
c语言·开发语言·网络·数据结构·c++·算法·leetcode
今天我刷leetcode了吗2 小时前
docker 配置同宿主机共同网段的IP 同时通过通网段的另一个电脑实现远程连接docker
tcp/ip·docker·电脑
科技象限2 小时前
电脑禁用U盘的四种简单方法(电脑怎么阻止u盘使用)
大数据·网络·电脑
东方隐侠安全团队-千里2 小时前
网安瞭望台第3期:俄黑客 TAG - 110组织与密码攻击手段分享
网络·chrome·web安全·网络安全
云计算DevOps-韩老师3 小时前
【网络云计算】2024第47周-每日【2024/11/21】周考-实操题-RAID6实操解析2
网络·云计算
耗同学一米八3 小时前
2024 年河北省职业院校技能大赛网络建设与运维赛项样题四
运维·网络