From ffbe848770d671ad8f09c423f62b27b2faad0dbb Mon Sep 17 00:00:00 2001 From: Timur Pocheptsov Date: Wed, 20 Sep 2017 15:56:31 +0200 Subject: QtNetwork (examples) - update broadcastsender Fix copyrights, update signal-slot connection syntax, use some simple C++11 features (member-initializers, 'auto'), delete some data-members (where a local variable is enough), where possible - use data-memebrs as sub-objects (instead of heap allocated). Task-number: QTBUG-60628 Change-Id: Ia440d8471eafb47481c0d010175c907037bae841 Reviewed-by: Edward Welbourne --- examples/network/broadcastsender/sender.cpp | 22 ++++++++++------------ examples/network/broadcastsender/sender.h | 19 ++++++++----------- 2 files changed, 18 insertions(+), 23 deletions(-) (limited to 'examples/network') diff --git a/examples/network/broadcastsender/sender.cpp b/examples/network/broadcastsender/sender.cpp index 344f898683..ee4896e9dd 100644 --- a/examples/network/broadcastsender/sender.cpp +++ b/examples/network/broadcastsender/sender.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,6 +50,7 @@ #include #include +#include #include "sender.h" @@ -60,23 +61,21 @@ Sender::Sender(QWidget *parent) statusLabel->setWordWrap(true); startButton = new QPushButton(tr("&Start")); - quitButton = new QPushButton(tr("&Quit")); + auto quitButton = new QPushButton(tr("&Quit")); - buttonBox = new QDialogButtonBox; + auto buttonBox = new QDialogButtonBox; buttonBox->addButton(startButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); - timer = new QTimer(this); //! [0] udpSocket = new QUdpSocket(this); //! [0] - messageNo = 1; - connect(startButton, SIGNAL(clicked()), this, SLOT(startBroadcasting())); - connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); - connect(timer, SIGNAL(timeout()), this, SLOT(broadcastDatagram())); + connect(startButton, &QPushButton::clicked, this, &Sender::startBroadcasting); + connect(quitButton, &QPushButton::clicked, this, &Sender::close); + connect(&timer, &QTimer::timeout, this, &Sender::broadcastDatagram); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(statusLabel); mainLayout->addWidget(buttonBox); setLayout(mainLayout); @@ -87,7 +86,7 @@ Sender::Sender(QWidget *parent) void Sender::startBroadcasting() { startButton->setEnabled(false); - timer->start(1000); + timer.start(1000); } void Sender::broadcastDatagram() @@ -95,8 +94,7 @@ void Sender::broadcastDatagram() statusLabel->setText(tr("Now broadcasting datagram %1").arg(messageNo)); //! [1] QByteArray datagram = "Broadcast message " + QByteArray::number(messageNo); - udpSocket->writeDatagram(datagram.data(), datagram.size(), - QHostAddress::Broadcast, 45454); + udpSocket->writeDatagram(datagram, QHostAddress::Broadcast, 45454); //! [1] ++messageNo; } diff --git a/examples/network/broadcastsender/sender.h b/examples/network/broadcastsender/sender.h index e9c1076dd3..f91c7769ec 100644 --- a/examples/network/broadcastsender/sender.h +++ b/examples/network/broadcastsender/sender.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -52,12 +52,11 @@ #define SENDER_H #include +#include QT_BEGIN_NAMESPACE -class QDialogButtonBox; class QLabel; class QPushButton; -class QTimer; class QUdpSocket; QT_END_NAMESPACE @@ -66,20 +65,18 @@ class Sender : public QWidget Q_OBJECT public: - Sender(QWidget *parent = 0); + explicit Sender(QWidget *parent = nullptr); private slots: void startBroadcasting(); void broadcastDatagram(); private: - QLabel *statusLabel; - QPushButton *startButton; - QPushButton *quitButton; - QDialogButtonBox *buttonBox; - QUdpSocket *udpSocket; - QTimer *timer; - int messageNo; + QLabel *statusLabel = nullptr; + QPushButton *startButton = nullptr; + QUdpSocket *udpSocket = nullptr; + QTimer timer; + int messageNo = 1; }; #endif -- cgit v1.2.3 From 390b28b240755c2636aa8fef96d5b0197a780a56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Thu, 21 Sep 2017 15:55:08 +0200 Subject: Slightly revamp the http example It was already revamped a fair bit 2 years ago Replaced Q_NULLPTR with nullptr. Added a minimum size to the progressbar dialog. Update the label if a redirect is rejected. Improve the overwrite dialog message. Replaced the documentation image. Task-number: QTBUG-60628 Change-Id: I0fb70d90e1d6ca84a8307bd6ea4ea1ce220feeaf Reviewed-by: Edward Welbourne Reviewed-by: Timur Pocheptsov --- examples/network/doc/images/http-example.png | Bin 7006 -> 8099 bytes examples/network/http/httpwindow.cpp | 46 ++++++++++++++++----------- examples/network/http/httpwindow.h | 8 ++--- 3 files changed, 32 insertions(+), 22 deletions(-) (limited to 'examples/network') diff --git a/examples/network/doc/images/http-example.png b/examples/network/doc/images/http-example.png index 16b0539b1b..c5f3ef1649 100644 Binary files a/examples/network/doc/images/http-example.png and b/examples/network/doc/images/http-example.png differ diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp index fddd2c809a..ec90b8f7fe 100644 --- a/examples/network/http/httpwindow.cpp +++ b/examples/network/http/httpwindow.cpp @@ -55,12 +55,12 @@ #include "httpwindow.h" #include "ui_authenticationdialog.h" -#ifndef QT_NO_SSL -static const char defaultUrl[] = "https://www.qt.io/"; +#if QT_CONFIG(ssl) +const char defaultUrl[] = "https://www.qt.io/"; #else -static const char defaultUrl[] = "http://www.qt.io/"; +const char defaultUrl[] = "http://www.qt.io/"; #endif -static const char defaultFileName[] = "index.html"; +const char defaultFileName[] = "index.html"; ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent) : QProgressDialog(parent) @@ -71,6 +71,7 @@ ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent) setMinimum(0); setValue(0); setMinimumDuration(0); + setMinimumSize(QSize(400, 75)); } void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes) @@ -87,8 +88,8 @@ HttpWindow::HttpWindow(QWidget *parent) , launchCheckBox(new QCheckBox("Launch file")) , defaultFileLineEdit(new QLineEdit(defaultFileName)) , downloadDirectoryLineEdit(new QLineEdit) - , reply(Q_NULLPTR) - , file(Q_NULLPTR) + , reply(nullptr) + , file(nullptr) , httpRequestAborted(false) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); @@ -174,15 +175,22 @@ void HttpWindow::downloadFile() if (fileName.isEmpty()) fileName = defaultFileName; QString downloadDirectory = QDir::cleanPath(downloadDirectoryLineEdit->text().trimmed()); - if (!downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir()) + bool useDirectory = !downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir(); + if (useDirectory) fileName.prepend(downloadDirectory + '/'); if (QFile::exists(fileName)) { if (QMessageBox::question(this, tr("Overwrite Existing File"), - tr("There already exists a file called %1 in " - "the current directory. Overwrite?").arg(fileName), - QMessageBox::Yes|QMessageBox::No, QMessageBox::No) - == QMessageBox::No) + tr("There already exists a file called %1%2." + " Overwrite?") + .arg(fileName, + useDirectory + ? QString() + : QStringLiteral(" in the current directory")), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) + == QMessageBox::No) { return; + } QFile::remove(fileName); } @@ -204,7 +212,7 @@ QFile *HttpWindow::openFileForWrite(const QString &fileName) tr("Unable to save the file %1: %2.") .arg(QDir::toNativeSeparators(fileName), file->errorString())); - return Q_NULLPTR; + return nullptr; } return file.take(); } @@ -224,12 +232,12 @@ void HttpWindow::httpFinished() fi.setFile(file->fileName()); file->close(); delete file; - file = Q_NULLPTR; + file = nullptr; } if (httpRequestAborted) { reply->deleteLater(); - reply = Q_NULLPTR; + reply = nullptr; return; } @@ -238,21 +246,23 @@ void HttpWindow::httpFinished() statusLabel->setText(tr("Download failed:\n%1.").arg(reply->errorString())); downloadButton->setEnabled(true); reply->deleteLater(); - reply = Q_NULLPTR; + reply = nullptr; return; } const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); reply->deleteLater(); - reply = Q_NULLPTR; + reply = nullptr; if (!redirectionTarget.isNull()) { const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl()); if (QMessageBox::question(this, tr("Redirect"), tr("Redirect to %1 ?").arg(redirectedUrl.toString()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { + QFile::remove(fi.absoluteFilePath()); downloadButton->setEnabled(true); + statusLabel->setText(tr("Download failed:\nRedirect rejected.")); return; } file = openFileForWrite(fi.absoluteFilePath()); @@ -286,7 +296,7 @@ void HttpWindow::enableDownloadButton() downloadButton->setEnabled(!urlLineEdit->text().isEmpty()); } -void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authenticator) +void HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator) { QDialog authenticationDialog; Ui::Dialog ui; @@ -306,7 +316,7 @@ void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authe } #ifndef QT_NO_SSL -void HttpWindow::sslErrors(QNetworkReply*,const QList &errors) +void HttpWindow::sslErrors(QNetworkReply *, const QList &errors) { QString errorString; foreach (const QSslError &error, errors) { diff --git a/examples/network/http/httpwindow.h b/examples/network/http/httpwindow.h index 3bb43dbf89..20ad2bb4da 100644 --- a/examples/network/http/httpwindow.h +++ b/examples/network/http/httpwindow.h @@ -71,7 +71,7 @@ class ProgressDialog : public QProgressDialog { Q_OBJECT public: - explicit ProgressDialog(const QUrl &url, QWidget *parent = Q_NULLPTR); + explicit ProgressDialog(const QUrl &url, QWidget *parent = nullptr); public slots: void networkReplyProgress(qint64 bytesRead, qint64 totalBytes); @@ -82,7 +82,7 @@ class HttpWindow : public QDialog Q_OBJECT public: - explicit HttpWindow(QWidget *parent = Q_NULLPTR); + explicit HttpWindow(QWidget *parent = nullptr); void startRequest(const QUrl &requestedUrl); @@ -92,9 +92,9 @@ private slots: void httpFinished(); void httpReadyRead(); void enableDownloadButton(); - void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *); + void slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator); #ifndef QT_NO_SSL - void sslErrors(QNetworkReply*,const QList &errors); + void sslErrors(QNetworkReply *, const QList &errors); #endif private: -- cgit v1.2.3 From ddb191e47a25a8a5c19cb01bec05c9538b22adf7 Mon Sep 17 00:00:00 2001 From: Timur Pocheptsov Date: Thu, 21 Sep 2017 13:24:07 +0200 Subject: QtNetwork (examples) - update secure socket client example This patch contains: - some cosmetic changes to make example look more like modern C++; - UI initialization code and SSL signals handling were split into separate member-functions; - useless checks 'if (socket)' were deleted; - widget's minimum size is now fixed + font size in 'CertInfo' dialog increased to make it readable. Change-Id: I7aadb78896832a989494d280d6da0635045f948c Reviewed-by: Timur Pocheptsov Reviewed-by: Edward Welbourne --- .../network/securesocketclient/certificateinfo.cpp | 22 ++- .../network/securesocketclient/certificateinfo.h | 13 +- .../network/securesocketclient/certificateinfo.ui | 2 +- examples/network/securesocketclient/main.cpp | 7 +- .../securesocketclient/securesocketclient.pro | 2 + examples/network/securesocketclient/sslclient.cpp | 168 +++++++++++---------- examples/network/securesocketclient/sslclient.h | 25 +-- examples/network/securesocketclient/sslclient.ui | 10 +- 8 files changed, 135 insertions(+), 114 deletions(-) (limited to 'examples/network') diff --git a/examples/network/securesocketclient/certificateinfo.cpp b/examples/network/securesocketclient/certificateinfo.cpp index c8cd86bc72..81429fc655 100644 --- a/examples/network/securesocketclient/certificateinfo.cpp +++ b/examples/network/securesocketclient/certificateinfo.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -57,8 +57,8 @@ CertificateInfo::CertificateInfo(QWidget *parent) form = new Ui_CertificateInfo; form->setupUi(this); - connect(form->certificationPathView, SIGNAL(currentIndexChanged(int)), - this, SLOT(updateCertificateInfo(int))); + connect(form->certificationPathView, QOverload::of(&QComboBox::currentIndexChanged), + this, &CertificateInfo::updateCertificateInfo); } CertificateInfo::~CertificateInfo() @@ -68,25 +68,23 @@ CertificateInfo::~CertificateInfo() void CertificateInfo::setCertificateChain(const QList &chain) { - this->chain = chain; + certificateChain = chain; form->certificationPathView->clear(); - - for (int i = 0; i < chain.size(); ++i) { - const QSslCertificate &cert = chain.at(i); + for (int i = 0; i < certificateChain.size(); ++i) { + const QSslCertificate &cert = certificateChain.at(i); form->certificationPathView->addItem(tr("%1%2 (%3)").arg(!i ? QString() : tr("Issued by: ")) .arg(cert.subjectInfo(QSslCertificate::Organization).join(QLatin1Char(' '))) .arg(cert.subjectInfo(QSslCertificate::CommonName).join(QLatin1Char(' ')))); } - form->certificationPathView->setCurrentIndex(0); } void CertificateInfo::updateCertificateInfo(int index) { form->certificateInfoView->clear(); - if (index >= 0 && index < chain.size()) { - const QSslCertificate &cert = chain.at(index); + if (index >= 0 && index < certificateChain.size()) { + const QSslCertificate &cert = certificateChain.at(index); QStringList lines; lines << tr("Organization: %1").arg(cert.subjectInfo(QSslCertificate::Organization).join(QLatin1Char(' '))) << tr("Subunit: %1").arg(cert.subjectInfo(QSslCertificate::OrganizationalUnitName).join(QLatin1Char(' '))) @@ -101,9 +99,7 @@ void CertificateInfo::updateCertificateInfo(int index) << tr("Issuer Locality: %1").arg(cert.issuerInfo(QSslCertificate::LocalityName).join(QLatin1Char(' '))) << tr("Issuer State/Province: %1").arg(cert.issuerInfo(QSslCertificate::StateOrProvinceName).join(QLatin1Char(' '))) << tr("Issuer Common Name: %1").arg(cert.issuerInfo(QSslCertificate::CommonName).join(QLatin1Char(' '))); - foreach (QString line, lines) + for (const auto &line : lines) form->certificateInfoView->addItem(line); - } else { - form->certificateInfoView->clear(); } } diff --git a/examples/network/securesocketclient/certificateinfo.h b/examples/network/securesocketclient/certificateinfo.h index abc56dfbcd..9e079c5603 100644 --- a/examples/network/securesocketclient/certificateinfo.h +++ b/examples/network/securesocketclient/certificateinfo.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,8 +51,9 @@ #ifndef CERTIFICATEINFO_H #define CERTIFICATEINFO_H -#include -#include +#include +#include +#include QT_BEGIN_NAMESPACE class Ui_CertificateInfo; @@ -62,7 +63,7 @@ class CertificateInfo : public QDialog { Q_OBJECT public: - CertificateInfo(QWidget *parent = 0); + explicit CertificateInfo(QWidget *parent = nullptr); ~CertificateInfo(); void setCertificateChain(const QList &chain); @@ -71,8 +72,8 @@ private slots: void updateCertificateInfo(int index); private: - Ui_CertificateInfo *form; - QList chain; + Ui_CertificateInfo *form = nullptr; + QList certificateChain; }; #endif diff --git a/examples/network/securesocketclient/certificateinfo.ui b/examples/network/securesocketclient/certificateinfo.ui index c5238eb3e1..3bea255e9e 100644 --- a/examples/network/securesocketclient/certificateinfo.ui +++ b/examples/network/securesocketclient/certificateinfo.ui @@ -42,7 +42,7 @@ - 8 + 10 diff --git a/examples/network/securesocketclient/main.cpp b/examples/network/securesocketclient/main.cpp index e6dc60736f..e9c413577f 100644 --- a/examples/network/securesocketclient/main.cpp +++ b/examples/network/securesocketclient/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,6 +50,9 @@ #include #include +#include + +QT_REQUIRE_CONFIG(ssl); #include "sslclient.h" @@ -61,7 +64,7 @@ int main(int argc, char **argv) if (!QSslSocket::supportsSsl()) { QMessageBox::information(0, "Secure Socket Client", - "This system does not support OpenSSL."); + "This system does not support SSL/TLS."); return -1; } diff --git a/examples/network/securesocketclient/securesocketclient.pro b/examples/network/securesocketclient/securesocketclient.pro index f13ed57247..98d2041754 100644 --- a/examples/network/securesocketclient/securesocketclient.pro +++ b/examples/network/securesocketclient/securesocketclient.pro @@ -1,3 +1,5 @@ +requires(qtHaveModule(network)) + HEADERS += certificateinfo.h \ sslclient.h SOURCES += certificateinfo.cpp \ diff --git a/examples/network/securesocketclient/sslclient.cpp b/examples/network/securesocketclient/sslclient.cpp index 46d1919fd0..afeec033ff 100644 --- a/examples/network/securesocketclient/sslclient.cpp +++ b/examples/network/securesocketclient/sslclient.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,29 +50,17 @@ #include "certificateinfo.h" #include "sslclient.h" + #include "ui_sslclient.h" #include "ui_sslerrors.h" -#include -#include -#include -#include -#include +#include SslClient::SslClient(QWidget *parent) - : QWidget(parent), socket(0), padLock(0), executingDialog(false) + : QWidget(parent) { - form = new Ui_Form; - form->setupUi(this); - form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size()); - form->sessionOutput->setHtml(tr("<not connected>")); - - connect(form->hostNameEdit, SIGNAL(textChanged(QString)), - this, SLOT(updateEnabledState())); - connect(form->connectButton, SIGNAL(clicked()), - this, SLOT(secureConnect())); - connect(form->sendButton, SIGNAL(clicked()), - this, SLOT(sendData())); + setupUi(); + setupSecureSocket(); } SslClient::~SslClient() @@ -82,17 +70,15 @@ SslClient::~SslClient() void SslClient::updateEnabledState() { - bool unconnected = !socket || socket->state() == QAbstractSocket::UnconnectedState; - + const bool unconnected = socket->state() == QAbstractSocket::UnconnectedState; form->hostNameEdit->setReadOnly(!unconnected); form->hostNameEdit->setFocusPolicy(unconnected ? Qt::StrongFocus : Qt::NoFocus); - form->hostNameLabel->setEnabled(unconnected); form->portBox->setEnabled(unconnected); form->portLabel->setEnabled(unconnected); form->connectButton->setEnabled(unconnected && !form->hostNameEdit->text().isEmpty()); - bool connected = socket && socket->state() == QAbstractSocket::ConnectedState; + const bool connected = socket->state() == QAbstractSocket::ConnectedState; form->sessionOutput->setEnabled(connected); form->sessionInput->setEnabled(connected); form->sessionInputLabel->setEnabled(connected); @@ -101,20 +87,6 @@ void SslClient::updateEnabledState() void SslClient::secureConnect() { - if (!socket) { - socket = new QSslSocket(this); - connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), - this, SLOT(socketStateChanged(QAbstractSocket::SocketState))); - connect(socket, SIGNAL(encrypted()), - this, SLOT(socketEncrypted())); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(socketError(QAbstractSocket::SocketError))); - connect(socket, SIGNAL(sslErrors(QList)), - this, SLOT(sslErrors(QList))); - connect(socket, SIGNAL(readyRead()), - this, SLOT(socketReadyRead())); - } - socket->connectToHostEncrypted(form->hostNameEdit->text(), form->portBox->value()); updateEnabledState(); } @@ -125,20 +97,18 @@ void SslClient::socketStateChanged(QAbstractSocket::SocketState state) return; updateEnabledState(); + if (state == QAbstractSocket::UnconnectedState) { + form->sessionInput->clear(); form->hostNameEdit->setPalette(QPalette()); form->hostNameEdit->setFocus(); form->cipherLabel->setText(tr("")); - if (padLock) - padLock->hide(); + padLock->hide(); } } void SslClient::socketEncrypted() { - if (!socket) - return; // might have disconnected already - form->sessionOutput->clear(); form->sessionInput->setFocus(); @@ -146,36 +116,12 @@ void SslClient::socketEncrypted() palette.setColor(QPalette::Base, QColor(255, 255, 192)); form->hostNameEdit->setPalette(palette); - QSslCipher ciph = socket->sessionCipher(); - QString cipher = QString("%1, %2 (%3/%4)").arg(ciph.authenticationMethod()) - .arg(ciph.name()).arg(ciph.usedBits()).arg(ciph.supportedBits());; - form->cipherLabel->setText(cipher); - - if (!padLock) { - padLock = new QToolButton; - padLock->setIcon(QIcon(":/encrypted.png")); -#ifndef QT_NO_CURSOR - padLock->setCursor(Qt::ArrowCursor); -#endif - padLock->setToolTip(tr("Display encryption details.")); - - int extent = form->hostNameEdit->height() - 2; - padLock->resize(extent, extent); - padLock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored); - - QHBoxLayout *layout = new QHBoxLayout(form->hostNameEdit); - layout->setMargin(form->hostNameEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth)); - layout->setSpacing(0); - layout->addStretch(); - layout->addWidget(padLock); - - form->hostNameEdit->setLayout(layout); - - connect(padLock, SIGNAL(clicked()), - this, SLOT(displayCertificateInfo())); - } else { - padLock->show(); - } + const QSslCipher cipher = socket->sessionCipher(); + const QString cipherInfo = QString("%1, %2 (%3/%4)").arg(cipher.authenticationMethod()) + .arg(cipher.name()).arg(cipher.usedBits()) + .arg(cipher.supportedBits());; + form->cipherLabel->setText(cipherInfo); + padLock->show(); } void SslClient::socketReadyRead() @@ -185,7 +131,7 @@ void SslClient::socketReadyRead() void SslClient::sendData() { - QString input = form->sessionInput->text(); + const QString input = form->sessionInput->text(); appendString(input + '\n'); socket->write(input.toUtf8() + "\r\n"); form->sessionInput->clear(); @@ -193,7 +139,12 @@ void SslClient::sendData() void SslClient::socketError(QAbstractSocket::SocketError) { + if (handlingSocketError) + return; + + handlingSocketError = true; QMessageBox::critical(this, tr("Connection error"), socket->errorString()); + handlingSocketError = false; } void SslClient::sslErrors(const QList &errors) @@ -201,10 +152,10 @@ void SslClient::sslErrors(const QList &errors) QDialog errorDialog(this); Ui_SslErrors ui; ui.setupUi(&errorDialog); - connect(ui.certificateChainButton, SIGNAL(clicked()), - this, SLOT(displayCertificateInfo())); + connect(ui.certificateChainButton, &QPushButton::clicked, + this, &SslClient::displayCertificateInfo); - foreach (const QSslError &error, errors) + for (const auto &error : errors) ui.sslErrorList->addItem(error.errorString()); executingDialog = true; @@ -219,10 +170,69 @@ void SslClient::sslErrors(const QList &errors) void SslClient::displayCertificateInfo() { - CertificateInfo *info = new CertificateInfo(this); - info->setCertificateChain(socket->peerCertificateChain()); - info->exec(); - info->deleteLater(); + CertificateInfo info; + info.setCertificateChain(socket->peerCertificateChain()); + info.exec(); +} + +void SslClient::setupUi() +{ + if (form) + return; + + form = new Ui_Form; + form->setupUi(this); + form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size()); + form->sessionOutput->setHtml(tr("<not connected>")); + + connect(form->hostNameEdit, SIGNAL(textChanged(QString)), + this, SLOT(updateEnabledState())); + connect(form->connectButton, SIGNAL(clicked()), + this, SLOT(secureConnect())); + connect(form->sendButton, SIGNAL(clicked()), + this, SLOT(sendData())); + + padLock = new QToolButton; + padLock->setIcon(QIcon(":/encrypted.png")); + connect(padLock, SIGNAL(clicked()), this, SLOT(displayCertificateInfo())); + +#if QT_CONFIG(cursor) + padLock->setCursor(Qt::ArrowCursor); +#endif + padLock->setToolTip(tr("Display encryption details.")); + + const int extent = form->hostNameEdit->height() - 2; + padLock->resize(extent, extent); + padLock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored); + + QHBoxLayout *layout = new QHBoxLayout(form->hostNameEdit); + layout->setMargin(form->hostNameEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth)); + layout->setSpacing(0); + layout->addStretch(); + layout->addWidget(padLock); + + form->hostNameEdit->setLayout(layout); + padLock->hide(); +} + +void SslClient::setupSecureSocket() +{ + if (socket) + return; + + socket = new QSslSocket(this); + + connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), + this, SLOT(socketStateChanged(QAbstractSocket::SocketState))); + connect(socket, SIGNAL(encrypted()), + this, SLOT(socketEncrypted())); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), + this, SLOT(socketError(QAbstractSocket::SocketError))); + connect(socket, SIGNAL(sslErrors(QList)), + this, SLOT(sslErrors(QList))); + connect(socket, SIGNAL(readyRead()), + this, SLOT(socketReadyRead())); + } void SslClient::appendString(const QString &line) diff --git a/examples/network/securesocketclient/sslclient.h b/examples/network/securesocketclient/sslclient.h index d3baefbc56..63fdbef77d 100644 --- a/examples/network/securesocketclient/sslclient.h +++ b/examples/network/securesocketclient/sslclient.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,13 +51,13 @@ #ifndef SSLCLIENT_H #define SSLCLIENT_H -#include -#include -#include +#include + +QT_REQUIRE_CONFIG(ssl); + +#include QT_BEGIN_NAMESPACE -class QSslSocket; -class QToolButton; class Ui_Form; QT_END_NAMESPACE @@ -65,7 +65,7 @@ class SslClient : public QWidget { Q_OBJECT public: - SslClient(QWidget *parent = 0); + explicit SslClient(QWidget *parent = nullptr); ~SslClient(); private slots: @@ -80,12 +80,15 @@ private slots: void displayCertificateInfo(); private: + void setupUi(); + void setupSecureSocket(); void appendString(const QString &line); - QSslSocket *socket; - QToolButton *padLock; - Ui_Form *form; - bool executingDialog; + QSslSocket *socket = nullptr; + QToolButton *padLock = nullptr; + Ui_Form *form = nullptr; + bool handlingSocketError = false; + bool executingDialog = false; }; #endif diff --git a/examples/network/securesocketclient/sslclient.ui b/examples/network/securesocketclient/sslclient.ui index 19bae83a09..7821b04e76 100644 --- a/examples/network/securesocketclient/sslclient.ui +++ b/examples/network/securesocketclient/sslclient.ui @@ -10,6 +10,12 @@ 320 + + + 343 + 320 + + Secure Socket Client @@ -114,8 +120,8 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"></p></body></html> +</style></head><body style=" font-family:'.SF NS Text'; font-size:13pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"><br /></p></body></html> -- cgit v1.2.3 From a732e16d5fd9dbf8a0289fec9f948b12e9ba2c19 Mon Sep 17 00:00:00 2001 From: Timur Pocheptsov Date: Wed, 20 Sep 2017 16:34:21 +0200 Subject: QtNetwork (examples) - update multicastsender Similar to broadcast sender: - where possible use local variables instead of data-members - where possible avoid heap-allocated objects, use sub-objects instead - change signal-slot connection syntax (and as a "bonus" - show our QOverload) Task-number: QTBUG-60628 Change-Id: I8cd4f888c1d0653bdc8591800e713bbd347ad2fb Reviewed-by: Edward Welbourne --- examples/network/multicastsender/sender.cpp | 41 +++++++++++------------------ examples/network/multicastsender/sender.h | 32 +++++++--------------- 2 files changed, 26 insertions(+), 47 deletions(-) (limited to 'examples/network') diff --git a/examples/network/multicastsender/sender.cpp b/examples/network/multicastsender/sender.cpp index 4aa65fee27..cb4bf45672 100644 --- a/examples/network/multicastsender/sender.cpp +++ b/examples/network/multicastsender/sender.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -48,43 +48,35 @@ ** ****************************************************************************/ -#include -#include - #include "sender.h" Sender::Sender(QWidget *parent) - : QDialog(parent) + : QDialog(parent), + groupAddress(QStringLiteral("239.255.43.21")) { - groupAddress = QHostAddress("239.255.43.21"); - statusLabel = new QLabel(tr("Ready to multicast datagrams to group %1 on port 45454").arg(groupAddress.toString())); - ttlLabel = new QLabel(tr("TTL for multicast datagrams:")); - ttlSpinBox = new QSpinBox; + auto ttlLabel = new QLabel(tr("TTL for multicast datagrams:")); + auto ttlSpinBox = new QSpinBox; ttlSpinBox->setRange(0, 255); - QHBoxLayout *ttlLayout = new QHBoxLayout; + auto ttlLayout = new QHBoxLayout; ttlLayout->addWidget(ttlLabel); ttlLayout->addWidget(ttlSpinBox); startButton = new QPushButton(tr("&Start")); - quitButton = new QPushButton(tr("&Quit")); + auto quitButton = new QPushButton(tr("&Quit")); - buttonBox = new QDialogButtonBox; + auto buttonBox = new QDialogButtonBox; buttonBox->addButton(startButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); - timer = new QTimer(this); - udpSocket = new QUdpSocket(this); - messageNo = 1; - - connect(ttlSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ttlChanged(int))); - connect(startButton, SIGNAL(clicked()), this, SLOT(startSending())); - connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); - connect(timer, SIGNAL(timeout()), this, SLOT(sendDatagram())); + connect(ttlSpinBox, QOverload::of(&QSpinBox::valueChanged), this, &Sender::ttlChanged); + connect(startButton, &QPushButton::clicked, this, &Sender::startSending); + connect(quitButton, &QPushButton::clicked, this, &Sender::close); + connect(&timer, &QTimer::timeout, this, &Sender::sendDatagram); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(statusLabel); mainLayout->addLayout(ttlLayout); mainLayout->addWidget(buttonBox); @@ -96,20 +88,19 @@ Sender::Sender(QWidget *parent) void Sender::ttlChanged(int newTtl) { - udpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, newTtl); + udpSocket.setSocketOption(QAbstractSocket::MulticastTtlOption, newTtl); } void Sender::startSending() { startButton->setEnabled(false); - timer->start(1000); + timer.start(1000); } void Sender::sendDatagram() { statusLabel->setText(tr("Now sending datagram %1").arg(messageNo)); QByteArray datagram = "Multicast message " + QByteArray::number(messageNo); - udpSocket->writeDatagram(datagram.data(), datagram.size(), - groupAddress, 45454); + udpSocket.writeDatagram(datagram, groupAddress, 45454); ++messageNo; } diff --git a/examples/network/multicastsender/sender.h b/examples/network/multicastsender/sender.h index 8e10f88c0d..5d8769790e 100644 --- a/examples/network/multicastsender/sender.h +++ b/examples/network/multicastsender/sender.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,24 +51,16 @@ #ifndef SENDER_H #define SENDER_H -#include -#include - -QT_BEGIN_NAMESPACE -class QDialogButtonBox; -class QLabel; -class QPushButton; -class QTimer; -class QUdpSocket; -class QSpinBox; -QT_END_NAMESPACE +#include +#include +#include class Sender : public QDialog { Q_OBJECT public: - Sender(QWidget *parent = 0); + explicit Sender(QWidget *parent = nullptr); private slots: void ttlChanged(int newTtl); @@ -76,16 +68,12 @@ private slots: void sendDatagram(); private: - QLabel *statusLabel; - QLabel *ttlLabel; - QSpinBox *ttlSpinBox; - QPushButton *startButton; - QPushButton *quitButton; - QDialogButtonBox *buttonBox; - QUdpSocket *udpSocket; - QTimer *timer; + QLabel *statusLabel = nullptr; + QPushButton *startButton = nullptr; + QUdpSocket udpSocket; + QTimer timer; QHostAddress groupAddress; - int messageNo; + int messageNo = 1; }; #endif -- cgit v1.2.3