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;



}
相关推荐
ProcessOn官方账号9 分钟前
如何绘制网络拓扑图?附详细分类解说和用户案例!
网络·职场和发展·流程图·拓扑学
Ven%33 分钟前
如何在防火墙上指定ip访问服务器上任何端口呢
linux·服务器·网络·深度学习·tcp/ip
神的孩子都在歌唱1 小时前
TCP/IP 模型中,网络层对 IP 地址的分配与路由选择
网络·tcp/ip·智能路由器
阿雄不会写代码1 小时前
ubuntu安装nginx
linux·服务器·网络
starstarzz2 小时前
计算机网络实验四:Cisco交换机配置VLAN
网络·计算机网络·智能路由器·vlan·虚拟局域网
网安墨雨3 小时前
常用网络协议
网络·网络协议
Tlzns3 小时前
Linux网络——UDP的运用
linux·网络·udp
黑客老陈3 小时前
新手小白如何挖掘cnvd通用漏洞之存储xss漏洞(利用xss钓鱼)
运维·服务器·前端·网络·安全·web3·xss
HSunR5 小时前
计算机网络
网络·计算机网络
ZoeLandia5 小时前
WebSocket | 背景 概念 原理 使用 优缺点及适用场景
网络·websocket·网络协议