添加或更改这段.h和.cpp代码使QT UDP发送的内容在C++控制台输出#include "UdpServer.h" UdpServer::UdpServer(QObject *parent) : QObject(parent) { initServer(); } UdpServer::~UdpServer() { } void UdpServer::initServer() { m_socket = new QUdpSocket(this); QObject::connect(m_socket, &QUdpSocket::readyRead, this, &UdpServer::readPendingDatagrams); m_socket->bind(6666, QUdpSocket::ShareAddress); } void UdpServer::readPendingDatagrams() { QByteArray arr; while (m_socket->hasPendingDatagrams()) { arr.resize(m_socket->bytesAvailable()); m_socket->readDatagram(arr.data(), arr.size(),&m_addr,&m_port); qDebug() << arr; } } #ifndef UDPSERVER_H #define UDPSERVER_H #include <QObject> #include <QUdpSocket> class UdpServer : public QObject { Q_OBJECT public: UdpServer(QObject *parent = nullptr); ~UdpServer(); private: void initServer(); private slots: void readPendingDatagrams(); private: QUdpSocket *m_socket; QHostAddress m_addr; quint16 m_port; }; #endif //UDPSERVER_H
时间: 2023-12-06 22:43:15 浏览: 142
test-udp.rar_UDP_UDP server client_c++ udp_udp server
下面是修改后的代码,将接收到的数据输出到控制台:
UdpServer.h
#ifndef UDPSERVER_H
#define UDPSERVER_H
#include <QObject>
#include <QUdpSocket>
class UdpServer : public QObject
{
Q_OBJECT
public:
UdpServer(QObject *parent = nullptr);
~UdpServer();
private:
void initServer();
private slots:
void readPendingDatagrams();
signals:
void dataReceived(const QByteArray& data); // 新增信号
private:
QUdpSocket *m_socket;
QHostAddress m_addr;
quint16 m_port;
};
#endif // UDPSERVER_H
UdpServer.cpp
#include "UdpServer.h"
#include <QDebug>
UdpServer::UdpServer(QObject *parent)
: QObject(parent)
{
initServer();
}
UdpServer::~UdpServer()
{
}
void UdpServer::initServer()
{
m_socket = new QUdpSocket(this);
QObject::connect(m_socket, &QUdpSocket::readyRead, this, &UdpServer::readPendingDatagrams);
m_socket->bind(6666, QUdpSocket::ShareAddress);
}
void UdpServer::readPendingDatagrams()
{
QByteArray arr;
while (m_socket->hasPendingDatagrams())
{
arr.resize(m_socket->pendingDatagramSize());
m_socket->readDatagram(arr.data(), arr.size(), &m_addr, &m_port);
qDebug() << arr;
emit dataReceived(arr); // 发送信号
}
}
在UdpServer类中添加了一个新的信号dataReceived,在readPendingDatagrams()函数中接收到数据后发送该信号,用于在外部处理接收到的数据。在控制台输出数据的代码不变,仅添加了信号的处理。
阅读全文