#include<QHostInfo>
#include<QNetworkInterface>
#include<QUdpSocket>
#include<QByteArray>
int port=5556; 定义端口号
发送端:
udpSend=new QUdpSocket;
//bing绑定IP和端口号,表示通过本机的某个IP和端口号发数据(IP本机必须有)
udpSend->bind(QHostAddress("192.168.0.34"),port);
QString str=ui->lineEdit_3->text();
arr=str.toLatin1();
//将数据发送出去,参数:数据内容,数据长度,对方(接收方)IP地址和端口
intn=udpSend->writeDatagram(arr,str.length(),QHostAddress("192.168.0.255"),port);
接收端
udpReceive=new QUdpSocket;
//绑定IP端口,实现只有发给该IP端口的数据才会被接收
udpReceive->bind(QHostAddress("192.168.0.231"),port);
//连接信号槽,只要有数据报过来,就会触发槽函数
connect(udpReceive,SIGNAL(readyRead()),this,SLOT(dataReceived()));
void Form::dataReceived()
{
while(udpReceive->hasPendingDatagrams())//判断是否有数据报可读
{
QByteArray datagram;//容器,用来保存数据报
//获得第一个数据报的长度
datagram.resize(udpReceive->pendingDatagramSize());
//将数据报保存到容器中,方便操作
udpReceive->readDatagram(datagram.data(),datagram.size());
ui->textEdit->setText(datagram.data());
}
}
报文大小不超过64KB
传输结构体数据
#pragma pack(1)字节对齐
#pragma pack()
INFO_SCAN info;
memset(&info,0,sizeof(info));
m_Socket->readDatagram((char*)&info,sizeof(info));
INFO_SCAN info;
info.orderType=TELESOFTWARE_CLOSE;
memset(&info.softwareName,0,sizeof(info.softwareName));
QString str=ui->software_name->text();
strcpy(info.softwareName,str.toLatin1());
int n=m_Socket->writeDatagram((char*)&info,sizeof(info),QHostAddress(ui->broadcast_address->text()),PORT);
发布了104 篇原创文章 ·
获赞 22 ·
访问量 4万+