UDP通信的原理不在累述,主要谈Qt UDP通信的实现。
1. pro文件中加入编译条件。
QT += network
2. 构造函数完成UDP scoket的是初始话实现如下。
udpSocet::udpSocet(const uint16_t port)
{
QString localHostName = QHostInfo::localHostName(); //获取本机IP
udpSocket = new QUdpSocket();
udpSocket->bind(QHostAddress(localHostName), port);
connect(udpSocket,SIGNAL(readyRead()),this,SLOT(recvMsgSlots()));
qDebug() << "--- udpSocket Init ---" ;
}
3. 槽函数具体实现,数据被存储在QByteArray中,通过信号与供其他类调用
void udpSocet::recvMsgSlots(void)
{
QByteArray msg;
while(udpSocket->hasPendingDatagrams())
{
msg.resize(int(udpSocket->pendingDatagramSize()));
udpSocket->readDatagram(msg.data(), msg.size());
qDebug() << "UDP Receive:" << msg.size();
qDebug() << "UDP Receive:" << msg.data();
emit receiveSignals(msg); //产生数据接收信号
}
}
4. 数据调用
udpSocet *udp = new udpSocet(this);
connect(udp,SIGNAL(receiveSignals(QByteArray)),this,SLOT(recSlots(QByteArray)));
void MainWindow::recSlots(QByteArray msg)
{
qDebug() << "signal Receive:" << msg.size();
qDebug() << "signal Receive:" << msg.data();
}
5. 获取发送方的IP和端口号
void udpSocet::recvMsgSlots(void)
{
QByteArray msg;
while(udpSocket->hasPendingDatagrams())
{
msg.resize(int(udpSocket->pendingDatagramSize()));
udpSocket->readDatagram(msg.data(), msg.size(),recAddr,recPort);
qDebug() << "UDP Receive IP:" << *recAddr << "PORT:" << *recPort;
qDebug() << "UDP Receive SIZE:" << msg.size();
qDebug() << "UDP Receive DATA:" << msg.data();
emit receiveSignals(msg); //产生数据接收信号
}
}
6. 测试结果