Add Qt network example source files
This commit is contained in:
parent
66491abb91
commit
e6c4a55aa4
|
@ -18,6 +18,7 @@ CONFIG += C++11 \
|
|||
INCLUDEPATH += src
|
||||
|
||||
SOURCES += \
|
||||
src/client.cpp \
|
||||
src/main.cpp \
|
||||
src/boarditem.cpp \
|
||||
src/gamecontroller.cpp \
|
||||
|
@ -27,11 +28,13 @@ SOURCES += \
|
|||
src/ninechessai_ab.cpp \
|
||||
src/ninechesswindow.cpp \
|
||||
src/pieceitem.cpp \
|
||||
src/aithread.cpp
|
||||
src/aithread.cpp \
|
||||
src/server.cpp
|
||||
|
||||
HEADERS += \
|
||||
src/HashNode.h \
|
||||
src/boarditem.h \
|
||||
src/client.h \
|
||||
src/config.h \
|
||||
src/gamecontroller.h \
|
||||
src/gamescene.h \
|
||||
|
@ -44,6 +47,7 @@ HEADERS += \
|
|||
src/pieceitem.h \
|
||||
src/manuallistview.h \
|
||||
src/aithread.h \
|
||||
src/server.h \
|
||||
src/zobrist.h
|
||||
|
||||
FORMS += \
|
||||
|
|
|
@ -375,6 +375,7 @@
|
|||
<ItemGroup>
|
||||
<ClCompile Include="src\aithread.cpp" />
|
||||
<ClCompile Include="src\boarditem.cpp" />
|
||||
<ClCompile Include="src\client.cpp" />
|
||||
<ClCompile Include="src\gamecontroller.cpp" />
|
||||
<ClCompile Include="src\gamescene.cpp" />
|
||||
<ClCompile Include="src\gameview.cpp" />
|
||||
|
@ -383,6 +384,7 @@
|
|||
<ClCompile Include="src\ninechessai_ab.cpp" />
|
||||
<ClCompile Include="src\ninechesswindow.cpp" />
|
||||
<ClCompile Include="src\pieceitem.cpp" />
|
||||
<ClCompile Include="src\server.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="resource.h" />
|
||||
|
@ -424,6 +426,12 @@
|
|||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include;release;\include;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\mkspecs\win32-msvc;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtWidgets;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtCore;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtGui;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtANGLE;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtMultimedia;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtNetwork;%(AdditionalIncludeDirectories)</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include;release;\include;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\mkspecs\win32-msvc;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtWidgets;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtCore;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtGui;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtANGLE;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtMultimedia;D:\Qt\Qt5.11.0\5.11.0\msvc2017_64\include\QtNetwork;%(AdditionalIncludeDirectories)</IncludePath>
|
||||
</QtMoc>
|
||||
<QtMoc Include="src\client.h">
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\debug;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\debug;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\release;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\release;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
</QtMoc>
|
||||
<ClInclude Include="src\config.h" />
|
||||
<ClInclude Include="src\graphicsconst.h" />
|
||||
<ClInclude Include="src\HashMap.h" />
|
||||
|
@ -503,6 +511,12 @@
|
|||
</AdditionalInputs>
|
||||
</CustomBuild>
|
||||
<ClInclude Include="src\ninechessai_ab.h" />
|
||||
<QtMoc Include="src\server.h">
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\debug;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\debug;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\release;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.\GeneratedFiles\$(ConfigurationName);.\GeneratedFiles;.;$(QTDIR)\include;.\release;\include;$(QTDIR)\mkspecs\win32-msvc;$(QTDIR)\include\QtWidgets;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtANGLE;$(QTDIR)\include\QtMultimedia;$(QTDIR)\include\QtNetwork</IncludePath>
|
||||
</QtMoc>
|
||||
<ClInclude Include="src\zobrist.h" />
|
||||
<ClInclude Include="ui_ninechesswindow.h" />
|
||||
</ItemGroup>
|
||||
|
|
|
@ -84,6 +84,12 @@
|
|||
<ClCompile Include="src\ninechessai_ab.cpp">
|
||||
<Filter>Model</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\client.cpp">
|
||||
<Filter>Control</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\server.cpp">
|
||||
<Filter>Control</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="resource.h">
|
||||
|
@ -294,5 +300,11 @@
|
|||
<QtMoc Include="src\ninechesswindow.h">
|
||||
<Filter>View</Filter>
|
||||
</QtMoc>
|
||||
<QtMoc Include="src\client.h">
|
||||
<Filter>Control</Filter>
|
||||
</QtMoc>
|
||||
<QtMoc Include="src\server.h">
|
||||
<Filter>Control</Filter>
|
||||
</QtMoc>
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -0,0 +1,270 @@
|
|||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2017 The Qt Company Ltd.
|
||||
** Contact: https://www.qt.io/licensing/
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** Commercial License Usage
|
||||
** Licensees holding valid commercial Qt licenses may use this file in
|
||||
** accordance with the commercial license agreement provided with the
|
||||
** Software or, alternatively, in accordance with the terms contained in
|
||||
** a written agreement between you and The Qt Company. For licensing terms
|
||||
** and conditions see https://www.qt.io/terms-conditions. For further
|
||||
** information use the contact form at https://www.qt.io/contact-us.
|
||||
**
|
||||
** BSD License Usage
|
||||
** Alternatively, you may use this file under the terms of the BSD license
|
||||
** as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of The Qt Company Ltd nor the names of its
|
||||
** contributors may be used to endorse or promote products derived
|
||||
** from this software without specific prior written permission.
|
||||
**
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
**
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
#include <QtWidgets>
|
||||
#include <QtNetwork>
|
||||
|
||||
#include "client.h"
|
||||
|
||||
//! [0]
|
||||
Client::Client(QWidget *parent)
|
||||
: QDialog(parent)
|
||||
, hostCombo(new QComboBox)
|
||||
, portLineEdit(new QLineEdit)
|
||||
, getFortuneButton(new QPushButton(tr("Get Fortune")))
|
||||
, tcpSocket(new QTcpSocket(this))
|
||||
{
|
||||
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
|
||||
//! [0]
|
||||
hostCombo->setEditable(true);
|
||||
// find out name of this machine
|
||||
QString name = QHostInfo::localHostName();
|
||||
if (!name.isEmpty()) {
|
||||
hostCombo->addItem(name);
|
||||
QString domain = QHostInfo::localDomainName();
|
||||
if (!domain.isEmpty())
|
||||
hostCombo->addItem(name + QChar('.') + domain);
|
||||
}
|
||||
if (name != QLatin1String("localhost"))
|
||||
hostCombo->addItem(QString("localhost"));
|
||||
// find out IP addresses of this machine
|
||||
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
|
||||
// add non-localhost addresses
|
||||
for (int i = 0; i < ipAddressesList.size(); ++i) {
|
||||
if (!ipAddressesList.at(i).isLoopback())
|
||||
hostCombo->addItem(ipAddressesList.at(i).toString());
|
||||
}
|
||||
// add localhost addresses
|
||||
for (int i = 0; i < ipAddressesList.size(); ++i) {
|
||||
if (ipAddressesList.at(i).isLoopback())
|
||||
hostCombo->addItem(ipAddressesList.at(i).toString());
|
||||
}
|
||||
|
||||
portLineEdit->setValidator(new QIntValidator(1, 65535, this));
|
||||
|
||||
auto hostLabel = new QLabel(tr("&Server name:"));
|
||||
hostLabel->setBuddy(hostCombo);
|
||||
auto portLabel = new QLabel(tr("S&erver port:"));
|
||||
portLabel->setBuddy(portLineEdit);
|
||||
|
||||
statusLabel = new QLabel(tr("This examples requires that you run the "
|
||||
"Fortune Server example as well."));
|
||||
|
||||
getFortuneButton->setDefault(true);
|
||||
getFortuneButton->setEnabled(false);
|
||||
|
||||
auto quitButton = new QPushButton(tr("Quit"));
|
||||
|
||||
auto buttonBox = new QDialogButtonBox;
|
||||
buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole);
|
||||
buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
|
||||
|
||||
//! [1]
|
||||
in.setDevice(tcpSocket);
|
||||
in.setVersion(QDataStream::Qt_4_0);
|
||||
//! [1]
|
||||
|
||||
connect(hostCombo, &QComboBox::editTextChanged,
|
||||
this, &Client::enableGetFortuneButton);
|
||||
connect(portLineEdit, &QLineEdit::textChanged,
|
||||
this, &Client::enableGetFortuneButton);
|
||||
connect(getFortuneButton, &QAbstractButton::clicked,
|
||||
this, &Client::requestNewFortune);
|
||||
connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close);
|
||||
//! [2] //! [3]
|
||||
connect(tcpSocket, &QIODevice::readyRead, this, &Client::readFortune);
|
||||
//! [2] //! [4]
|
||||
connect(tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),
|
||||
//! [3]
|
||||
this, &Client::displayError);
|
||||
//! [4]
|
||||
|
||||
QGridLayout *mainLayout = nullptr;
|
||||
if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) {
|
||||
auto outerVerticalLayout = new QVBoxLayout(this);
|
||||
outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
|
||||
auto outerHorizontalLayout = new QHBoxLayout;
|
||||
outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
|
||||
auto groupBox = new QGroupBox(QGuiApplication::applicationDisplayName());
|
||||
mainLayout = new QGridLayout(groupBox);
|
||||
outerHorizontalLayout->addWidget(groupBox);
|
||||
outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
|
||||
outerVerticalLayout->addLayout(outerHorizontalLayout);
|
||||
outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
|
||||
} else {
|
||||
mainLayout = new QGridLayout(this);
|
||||
}
|
||||
mainLayout->addWidget(hostLabel, 0, 0);
|
||||
mainLayout->addWidget(hostCombo, 0, 1);
|
||||
mainLayout->addWidget(portLabel, 1, 0);
|
||||
mainLayout->addWidget(portLineEdit, 1, 1);
|
||||
mainLayout->addWidget(statusLabel, 2, 0, 1, 2);
|
||||
mainLayout->addWidget(buttonBox, 3, 0, 1, 2);
|
||||
|
||||
setWindowTitle(QGuiApplication::applicationDisplayName());
|
||||
portLineEdit->setFocus();
|
||||
|
||||
QNetworkConfigurationManager manager;
|
||||
if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
|
||||
// Get saved network configuration
|
||||
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
|
||||
settings.beginGroup(QLatin1String("QtNetwork"));
|
||||
const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
|
||||
settings.endGroup();
|
||||
|
||||
// If the saved network configuration is not currently discovered use the system default
|
||||
QNetworkConfiguration config = manager.configurationFromIdentifier(id);
|
||||
if ((config.state() & QNetworkConfiguration::Discovered) !=
|
||||
QNetworkConfiguration::Discovered) {
|
||||
config = manager.defaultConfiguration();
|
||||
}
|
||||
|
||||
networkSession = new QNetworkSession(config, this);
|
||||
connect(networkSession, &QNetworkSession::opened, this, &Client::sessionOpened);
|
||||
|
||||
getFortuneButton->setEnabled(false);
|
||||
statusLabel->setText(tr("Opening network session."));
|
||||
networkSession->open();
|
||||
}
|
||||
//! [5]
|
||||
}
|
||||
//! [5]
|
||||
|
||||
//! [6]
|
||||
void Client::requestNewFortune()
|
||||
{
|
||||
getFortuneButton->setEnabled(false);
|
||||
tcpSocket->abort();
|
||||
//! [7]
|
||||
tcpSocket->connectToHost(hostCombo->currentText(),
|
||||
portLineEdit->text().toInt());
|
||||
//! [7]
|
||||
}
|
||||
//! [6]
|
||||
|
||||
//! [8]
|
||||
void Client::readFortune()
|
||||
{
|
||||
in.startTransaction();
|
||||
|
||||
QString nextFortune;
|
||||
in >> nextFortune;
|
||||
|
||||
if (!in.commitTransaction())
|
||||
return;
|
||||
|
||||
if (nextFortune == currentFortune) {
|
||||
QTimer::singleShot(0, this, &Client::requestNewFortune);
|
||||
return;
|
||||
}
|
||||
|
||||
currentFortune = nextFortune;
|
||||
statusLabel->setText(currentFortune);
|
||||
getFortuneButton->setEnabled(true);
|
||||
}
|
||||
//! [8]
|
||||
|
||||
//! [13]
|
||||
void Client::displayError(QAbstractSocket::SocketError socketError)
|
||||
{
|
||||
switch (socketError) {
|
||||
case QAbstractSocket::RemoteHostClosedError:
|
||||
break;
|
||||
case QAbstractSocket::HostNotFoundError:
|
||||
QMessageBox::information(this, tr("Fortune Client"),
|
||||
tr("The host was not found. Please check the "
|
||||
"host name and port settings."));
|
||||
break;
|
||||
case QAbstractSocket::ConnectionRefusedError:
|
||||
QMessageBox::information(this, tr("Fortune Client"),
|
||||
tr("The connection was refused by the peer. "
|
||||
"Make sure the fortune server is running, "
|
||||
"and check that the host name and port "
|
||||
"settings are correct."));
|
||||
break;
|
||||
default:
|
||||
QMessageBox::information(this, tr("Fortune Client"),
|
||||
tr("The following error occurred: %1.")
|
||||
.arg(tcpSocket->errorString()));
|
||||
}
|
||||
|
||||
getFortuneButton->setEnabled(true);
|
||||
}
|
||||
//! [13]
|
||||
|
||||
void Client::enableGetFortuneButton()
|
||||
{
|
||||
getFortuneButton->setEnabled((!networkSession || networkSession->isOpen()) &&
|
||||
!hostCombo->currentText().isEmpty() &&
|
||||
!portLineEdit->text().isEmpty());
|
||||
|
||||
}
|
||||
|
||||
void Client::sessionOpened()
|
||||
{
|
||||
// Save the used configuration
|
||||
QNetworkConfiguration config = networkSession->configuration();
|
||||
QString id;
|
||||
if (config.type() == QNetworkConfiguration::UserChoice)
|
||||
id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
|
||||
else
|
||||
id = config.identifier();
|
||||
|
||||
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
|
||||
settings.beginGroup(QLatin1String("QtNetwork"));
|
||||
settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
|
||||
settings.endGroup();
|
||||
|
||||
statusLabel->setText(tr("This examples requires that you run the "
|
||||
"Fortune Server example as well."));
|
||||
|
||||
enableGetFortuneButton();
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2017 The Qt Company Ltd.
|
||||
** Contact: https://www.qt.io/licensing/
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** Commercial License Usage
|
||||
** Licensees holding valid commercial Qt licenses may use this file in
|
||||
** accordance with the commercial license agreement provided with the
|
||||
** Software or, alternatively, in accordance with the terms contained in
|
||||
** a written agreement between you and The Qt Company. For licensing terms
|
||||
** and conditions see https://www.qt.io/terms-conditions. For further
|
||||
** information use the contact form at https://www.qt.io/contact-us.
|
||||
**
|
||||
** BSD License Usage
|
||||
** Alternatively, you may use this file under the terms of the BSD license
|
||||
** as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of The Qt Company Ltd nor the names of its
|
||||
** contributors may be used to endorse or promote products derived
|
||||
** from this software without specific prior written permission.
|
||||
**
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
**
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef CLIENT_H
|
||||
#define CLIENT_H
|
||||
|
||||
#include <QDataStream>
|
||||
#include <QDialog>
|
||||
#include <QTcpSocket>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
class QComboBox;
|
||||
class QLabel;
|
||||
class QLineEdit;
|
||||
class QPushButton;
|
||||
class QTcpSocket;
|
||||
class QNetworkSession;
|
||||
QT_END_NAMESPACE
|
||||
|
||||
//! [0]
|
||||
class Client : public QDialog
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit Client(QWidget *parent = nullptr);
|
||||
|
||||
private slots:
|
||||
void requestNewFortune();
|
||||
void readFortune();
|
||||
void displayError(QAbstractSocket::SocketError socketError);
|
||||
void enableGetFortuneButton();
|
||||
void sessionOpened();
|
||||
|
||||
private:
|
||||
QComboBox *hostCombo = nullptr;
|
||||
QLineEdit *portLineEdit = nullptr;
|
||||
QLabel *statusLabel = nullptr;
|
||||
QPushButton *getFortuneButton = nullptr;
|
||||
|
||||
QTcpSocket *tcpSocket = nullptr;
|
||||
QDataStream in;
|
||||
QString currentFortune;
|
||||
|
||||
QNetworkSession *networkSession = nullptr;
|
||||
};
|
||||
//! [0]
|
||||
|
||||
#endif
|
|
@ -0,0 +1,197 @@
|
|||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2017 The Qt Company Ltd.
|
||||
** Contact: https://www.qt.io/licensing/
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** Commercial License Usage
|
||||
** Licensees holding valid commercial Qt licenses may use this file in
|
||||
** accordance with the commercial license agreement provided with the
|
||||
** Software or, alternatively, in accordance with the terms contained in
|
||||
** a written agreement between you and The Qt Company. For licensing terms
|
||||
** and conditions see https://www.qt.io/terms-conditions. For further
|
||||
** information use the contact form at https://www.qt.io/contact-us.
|
||||
**
|
||||
** BSD License Usage
|
||||
** Alternatively, you may use this file under the terms of the BSD license
|
||||
** as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of The Qt Company Ltd nor the names of its
|
||||
** contributors may be used to endorse or promote products derived
|
||||
** from this software without specific prior written permission.
|
||||
**
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
**
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
#include <QtWidgets>
|
||||
#include <QtNetwork>
|
||||
#include <QtCore>
|
||||
|
||||
#include "server.h"
|
||||
|
||||
Server::Server(QWidget *parent)
|
||||
: QDialog(parent)
|
||||
, statusLabel(new QLabel)
|
||||
{
|
||||
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
|
||||
statusLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
|
||||
|
||||
QNetworkConfigurationManager manager;
|
||||
if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
|
||||
// Get saved network configuration
|
||||
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
|
||||
settings.beginGroup(QLatin1String("QtNetwork"));
|
||||
const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
|
||||
settings.endGroup();
|
||||
|
||||
// If the saved network configuration is not currently discovered use the system default
|
||||
QNetworkConfiguration config = manager.configurationFromIdentifier(id);
|
||||
if ((config.state() & QNetworkConfiguration::Discovered) !=
|
||||
QNetworkConfiguration::Discovered) {
|
||||
config = manager.defaultConfiguration();
|
||||
}
|
||||
|
||||
networkSession = new QNetworkSession(config, this);
|
||||
connect(networkSession, &QNetworkSession::opened, this, &Server::sessionOpened);
|
||||
|
||||
statusLabel->setText(tr("Opening network session."));
|
||||
networkSession->open();
|
||||
} else {
|
||||
sessionOpened();
|
||||
}
|
||||
|
||||
//! [2]
|
||||
fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
|
||||
<< tr("You've got to think about tomorrow.")
|
||||
<< tr("You will be surprised by a loud noise.")
|
||||
<< tr("You will feel hungry again in another hour.")
|
||||
<< tr("You might have mail.")
|
||||
<< tr("You cannot kill time without injuring eternity.")
|
||||
<< tr("Computers are not intelligent. They only think they are.");
|
||||
//! [2]
|
||||
auto quitButton = new QPushButton(tr("Quit"));
|
||||
quitButton->setAutoDefault(false);
|
||||
connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close);
|
||||
//! [3]
|
||||
connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendFortune);
|
||||
//! [3]
|
||||
|
||||
auto buttonLayout = new QHBoxLayout;
|
||||
buttonLayout->addStretch(1);
|
||||
buttonLayout->addWidget(quitButton);
|
||||
buttonLayout->addStretch(1);
|
||||
|
||||
QVBoxLayout *mainLayout = nullptr;
|
||||
if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) {
|
||||
auto outerVerticalLayout = new QVBoxLayout(this);
|
||||
outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
|
||||
auto outerHorizontalLayout = new QHBoxLayout;
|
||||
outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
|
||||
auto groupBox = new QGroupBox(QGuiApplication::applicationDisplayName());
|
||||
mainLayout = new QVBoxLayout(groupBox);
|
||||
outerHorizontalLayout->addWidget(groupBox);
|
||||
outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
|
||||
outerVerticalLayout->addLayout(outerHorizontalLayout);
|
||||
outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
|
||||
} else {
|
||||
mainLayout = new QVBoxLayout(this);
|
||||
}
|
||||
|
||||
mainLayout->addWidget(statusLabel);
|
||||
mainLayout->addLayout(buttonLayout);
|
||||
|
||||
setWindowTitle(QGuiApplication::applicationDisplayName());
|
||||
}
|
||||
|
||||
void Server::sessionOpened()
|
||||
{
|
||||
// Save the used configuration
|
||||
if (networkSession) {
|
||||
QNetworkConfiguration config = networkSession->configuration();
|
||||
QString id;
|
||||
if (config.type() == QNetworkConfiguration::UserChoice)
|
||||
id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
|
||||
else
|
||||
id = config.identifier();
|
||||
|
||||
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
|
||||
settings.beginGroup(QLatin1String("QtNetwork"));
|
||||
settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
|
||||
settings.endGroup();
|
||||
}
|
||||
|
||||
//! [0] //! [1]
|
||||
tcpServer = new QTcpServer(this);
|
||||
if (!tcpServer->listen()) {
|
||||
QMessageBox::critical(this, tr("Fortune Server"),
|
||||
tr("Unable to start the server: %1.")
|
||||
.arg(tcpServer->errorString()));
|
||||
close();
|
||||
return;
|
||||
}
|
||||
//! [0]
|
||||
QString ipAddress;
|
||||
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
|
||||
// use the first non-localhost IPv4 address
|
||||
for (int i = 0; i < ipAddressesList.size(); ++i) {
|
||||
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
|
||||
ipAddressesList.at(i).toIPv4Address()) {
|
||||
ipAddress = ipAddressesList.at(i).toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
// if we did not find one, use IPv4 localhost
|
||||
if (ipAddress.isEmpty())
|
||||
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
|
||||
statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
|
||||
"Run the Fortune Client example now.")
|
||||
.arg(ipAddress).arg(tcpServer->serverPort()));
|
||||
//! [1]
|
||||
}
|
||||
|
||||
//! [4]
|
||||
void Server::sendFortune()
|
||||
{
|
||||
//! [5]
|
||||
QByteArray block;
|
||||
QDataStream out(&block, QIODevice::WriteOnly);
|
||||
out.setVersion(QDataStream::Qt_5_10);
|
||||
|
||||
out << fortunes[QRandomGenerator::global()->bounded(fortunes.size())];
|
||||
//! [4] //! [7]
|
||||
|
||||
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
|
||||
connect(clientConnection, &QAbstractSocket::disconnected,
|
||||
clientConnection, &QObject::deleteLater);
|
||||
//! [7] //! [8]
|
||||
|
||||
clientConnection->write(block);
|
||||
clientConnection->disconnectFromHost();
|
||||
//! [5]
|
||||
}
|
||||
//! [8]
|
|
@ -0,0 +1,84 @@
|
|||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2017 The Qt Company Ltd.
|
||||
** Contact: https://www.qt.io/licensing/
|
||||
**
|
||||
** This file is part of the examples of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:BSD$
|
||||
** Commercial License Usage
|
||||
** Licensees holding valid commercial Qt licenses may use this file in
|
||||
** accordance with the commercial license agreement provided with the
|
||||
** Software or, alternatively, in accordance with the terms contained in
|
||||
** a written agreement between you and The Qt Company. For licensing terms
|
||||
** and conditions see https://www.qt.io/terms-conditions. For further
|
||||
** information use the contact form at https://www.qt.io/contact-us.
|
||||
**
|
||||
** BSD License Usage
|
||||
** Alternatively, you may use this file under the terms of the BSD license
|
||||
** as follows:
|
||||
**
|
||||
** "Redistribution and use in source and binary forms, with or without
|
||||
** modification, are permitted provided that the following conditions are
|
||||
** met:
|
||||
** * Redistributions of source code must retain the above copyright
|
||||
** notice, this list of conditions and the following disclaimer.
|
||||
** * Redistributions in binary form must reproduce the above copyright
|
||||
** notice, this list of conditions and the following disclaimer in
|
||||
** the documentation and/or other materials provided with the
|
||||
** distribution.
|
||||
** * Neither the name of The Qt Company Ltd nor the names of its
|
||||
** contributors may be used to endorse or promote products derived
|
||||
** from this software without specific prior written permission.
|
||||
**
|
||||
**
|
||||
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
**
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef SERVER_H
|
||||
#define SERVER_H
|
||||
|
||||
#include <QDialog>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
class QLabel;
|
||||
class QTcpServer;
|
||||
class QNetworkSession;
|
||||
QT_END_NAMESPACE
|
||||
|
||||
//! [0]
|
||||
class Server : public QDialog
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit Server(QWidget *parent = nullptr);
|
||||
|
||||
private slots:
|
||||
void sessionOpened();
|
||||
void sendFortune();
|
||||
|
||||
private:
|
||||
QLabel *statusLabel = nullptr;
|
||||
QTcpServer *tcpServer = nullptr;
|
||||
QVector<QString> fortunes;
|
||||
QNetworkSession *networkSession = nullptr;
|
||||
};
|
||||
//! [0]
|
||||
|
||||
#endif
|
Loading…
Reference in New Issue