HTTP
需要用到的类: QNetworkRequest QNetworkAccessManager QNetworkReply
{
QString x = "";
QString url = QString("https://<ip address>/<command>/key1=value&key2=value");
QNetworkRequest request;
request.setUrl(QUrl(url));
QNetworkAccessManager naManager(this);
QNetworkReply* reply = naManager.get(request);
connect(reply, &QNetworkReply::finished, this, [this,reply](){
if(reply->error() != QNetworkReply::NoError){
reply->deleteLater();
emit sigHttpRequestFinished();
return;
}
qDebug()<<reply->readAll();
emit sigHttpRequestFinished();
reply->deleteLater();
});
QEventLoop loop;
connect(this,SIGNAL(sigHttpRequestFinished()),&loop,SLOT(quit()));
loop.exec();
}
自定义reply超时时间
void replyTimeout(QNetworkReply* reply, int timeout)
{
QTimer::singleShot(timeout,this,[this](){
if(reply) reply->close();
});
}
UDP组播
先绑定端口,
udpSocket->bind(QHostAddress::AnyIPv4,groupPort,QUdpSocket::SareAddress)
然后使用函数加入、退出组播
bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress)
bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress)
发送和接受组播数据报
- 发送:
writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port) - 接收:
qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *address = nullptr, quint16 *port = nullptr) QNetworkDatagram receiveDatagram(qint64 maxSize = -1) 获取QNetworkDatagram 的senderAddress和senderPort和data
void PepperlFuchsIPConfigDlg::SSDPsearch()
{
QString searchRequest = "M-SEARCH * HTTP/1.1\r\n"
"H0ST: 239.255.255.250:1900\r\n"
"ST: urn:pepperl-fuchs-com:device:R2000:1\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: 1\r\n";
quint16 port = 1900;
QString hostAddress = "239.255.255.250";
QHostAddress groupAddress(hostAddress);
_udpSocket = new QUdpSocket(this);
_udpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption,1);
_udpSocket->bind(QHostAddress::AnyIPv4,port,QUdpSocket::ShareAddress);
_udpSocket->joinMulticastGroup(groupAddress);
_udpSocket->writeDatagram(searchRequest.toUtf8(),groupAddress,port);
connect(_udpSocket,&QUdpSocket::readyRead,this,[this](){
QNetworkDatagram datagram = _udpSocket->receiveDatagram();
qDebug()<<"peer address:"<<datagram.senderAddress();
qDebug()<<"peer port:"<<datagram.senderPort();
qDebug()<<"peer data:"<<datagram.data();
});
}
void PepperlFuchsIPConfigDlg::SSDPsearchOff()
{
_udpSocket->leaveMulticastGroup(_groupAddress);
_udpSocket->abort();
_udpSocket->deleteLater();
_udpSocket = Q_NULLPTR;
}
|