|
使用writeDatagram()发送一个数据报给485模块,485模块收到后将对应传感器的信息(9字节的16进制)返回。现在的问题是,成功发送数据报,可是却接收不到。代码如下:- #include<QNetworkInterface>
- #include<QMessageBox>
- #include<QHostInfo>
- #include"networkinformation.h"
- NetworkInformation::NetworkInformation(QWidget *parent)
- :QWidget(parent)
- {
- hostLabel=new QLabel(tr("tem:"));
- LineEditLocalHostName=new QLineEdit;
- ipLabel=new QLabel(tr("hum:"));
- LineEditAddress=new QLineEdit;
- detailBtn=new QPushButton(tr("send"));
- mainLayout=new QGridLayout(this);
- mainLayout->addWidget(hostLabel,0,0);
- mainLayout->addWidget(LineEditLocalHostName,0,1);
- mainLayout->addWidget(ipLabel,1,0);
- mainLayout->addWidget(LineEditAddress,1,1);
- mainLayout->addWidget(detailBtn,2,0,1,2);
- setWindowTitle("Network");
- connect(detailBtn,SIGNAL(clicked()),this,SLOT(slotDetail()));
-
- //port=8000;
- udpsocket=new QUdpSocket(this);
- receiver=new QUdpSocket(this);
- //receiver->bind(8000,QUdpSocket::ShareAddress);
- connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
- }
- void NetworkInformation::slotDetail()
- {
- //char str[128]={0x01,0x04,0x00,0x00,0x00,0x02,0x71,0xcb};
- QByteArray ba;
- ba.resize(8);
- ba[0]=0x01;
- ba[1]=0x04;
- ba[2]=0x00;
- ba[3]=0x00;
- ba[4]=0x00;
- ba[5]=0x02;
- ba[6]=0x71;
- ba[7]=0xcb;
- qint64 len;
- QHostAddress adr=QHostAddress("192.168.1.33");
- //len=udpsocket->writeDatagram(str,32,adr,port);
- len=udpsocket->writeDatagram(ba,adr,8000);
- if(len==-1)
- {
- QMessageBox::information(this,tr("error"),tr("writedatagram failed!"));
- return;
- }
- qDebug()<<"yes"<<len;
- }
- void NetworkInformation::processPendingDatagram()
- {
- while(receiver->hasPendingDatagrams())
- {
- qDebug()<<"hasPendingDatagrams";
- QByteArray datagram;
- qint64 rlen;
- datagram.resize(receiver->pendingDatagramSize());
- rlen=receiver->readDatagram(datagram.data(),datagram.size());
- if(rlen==-1)
- {
- QMessageBox::information(this,tr("error"),tr("readdatagram failed!"));
- return;
- }
- }
- }
复制代码 |
|