QT UDP通信接受发送数据
首先在.pro文件中加入 QT +=network;
客户端
1.建立socket
sender = new QUdpSocket(this);
2.绑定端口
sender->bind(45453,QUdpSocket::ShareAddress);
3.接受数据
connect(sender,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
void processPendingDatagram() //处理等待的数据报 { while(sender->hasPendingDatagrams()) //拥有等待的数据报 { QByteArray datagram; //拥于存放接收的数据报 datagram.resize(sender->pendingDatagramSize()); sender->readDatagram(datagram.data(),datagram.size()); unsigned short size = datagram.size(); unsigned char msg[10] = {0}; memcpy(msg, datagram.data(), size); unsigned short arr = msg[0]; arr = (arr<<8)+msg[1]; qDebug()<<msg[0]<<msg[1]<<msg[2]<<msg[3]; } }
4.发送数据
sender->writeDatagram((char*)msg,3, QHostAddress::Broadcast,45454);
服务端
1.建立Socket
receiver = new QUdpSocket(this);
2.绑定端口
receiver->bind(45454,QUdpSocket::ShareAddress);
3.接受数据
connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
void processPendingDatagram() //处理等待的数据报 { while(receiver->hasPendingDatagrams()) //拥有等待的数据报 { QByteArray datagram; //拥于存放接收的数据报 datagram.resize(receiver->pendingDatagramSize()); receiver->readDatagram(datagram.data(),datagram.size()); unsigned short size = datagram.size(); unsigned char msg[10] = {0}; memcpy(msg, datagram.data(), size); qDebug()<<msg[0]<<msg[1]<<msg[2]<<msg[3]; } }
4.发送数据
receiver->writeDatagram((char*)msg,3, QHostAddress::Broadcast,45453);