1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include <QtWidgets>
52#include <QtNetwork>
53#include <QtCore>
54
55#include "server.h"
56
57Server::Server(QWidget *parent)
58 : QDialog(parent)
59 , statusLabel(new QLabel)
60{
61 setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
62 statusLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
63
64 QNetworkConfigurationManager manager;
65 if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
66 // Get saved network configuration
67 QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
68 settings.beginGroup(QLatin1String("QtNetwork"));
69 const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
70 settings.endGroup();
71
72 // If the saved network configuration is not currently discovered use the system default
73 QNetworkConfiguration config = manager.configurationFromIdentifier(id);
74 if ((config.state() & QNetworkConfiguration::Discovered) !=
75 QNetworkConfiguration::Discovered) {
76 config = manager.defaultConfiguration();
77 }
78
79 networkSession = new QNetworkSession(config, this);
80 connect(networkSession, &QNetworkSession::opened, this, &Server::sessionOpened);
81
82 statusLabel->setText(tr("Opening network session."));
83 networkSession->open();
84 } else {
85 sessionOpened();
86 }
87
88 //! [2]
89 fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
90 << tr("You've got to think about tomorrow.")
91 << tr("You will be surprised by a loud noise.")
92 << tr("You will feel hungry again in another hour.")
93 << tr("You might have mail.")
94 << tr("You cannot kill time without injuring eternity.")
95 << tr("Computers are not intelligent. They only think they are.");
96 //! [2]
97 auto quitButton = new QPushButton(tr("Quit"));
98 quitButton->setAutoDefault(false);
99 connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close);
100 //! [3]
101 connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendFortune);
102 //! [3]
103
104 auto buttonLayout = new QHBoxLayout;
105 buttonLayout->addStretch(1);
106 buttonLayout->addWidget(quitButton);
107 buttonLayout->addStretch(1);
108
109 QVBoxLayout *mainLayout = nullptr;
110 if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) {
111 auto outerVerticalLayout = new QVBoxLayout(this);
112 outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
113 auto outerHorizontalLayout = new QHBoxLayout;
114 outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
115 auto groupBox = new QGroupBox(QGuiApplication::applicationDisplayName());
116 mainLayout = new QVBoxLayout(groupBox);
117 outerHorizontalLayout->addWidget(groupBox);
118 outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
119 outerVerticalLayout->addLayout(outerHorizontalLayout);
120 outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
121 } else {
122 mainLayout = new QVBoxLayout(this);
123 }
124
125 mainLayout->addWidget(statusLabel);
126 mainLayout->addLayout(buttonLayout);
127
128 setWindowTitle(QGuiApplication::applicationDisplayName());
129}
130
131void Server::sessionOpened()
132{
133 // Save the used configuration
134 if (networkSession) {
135 QNetworkConfiguration config = networkSession->configuration();
136 QString id;
137 if (config.type() == QNetworkConfiguration::UserChoice)
138 id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
139 else
140 id = config.identifier();
141
142 QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
143 settings.beginGroup(QLatin1String("QtNetwork"));
144 settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
145 settings.endGroup();
146 }
147
148//! [0] //! [1]
149 tcpServer = new QTcpServer(this);
150 if (!tcpServer->listen()) {
151 QMessageBox::critical(this, tr("Fortune Server"),
152 tr("Unable to start the server: %1.")
153 .arg(tcpServer->errorString()));
154 close();
155 return;
156 }
157//! [0]
158 QString ipAddress;
159 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
160 // use the first non-localhost IPv4 address
161 for (int i = 0; i < ipAddressesList.size(); ++i) {
162 if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
163 ipAddressesList.at(i).toIPv4Address()) {
164 ipAddress = ipAddressesList.at(i).toString();
165 break;
166 }
167 }
168 // if we did not find one, use IPv4 localhost
169 if (ipAddress.isEmpty())
170 ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
171 statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
172 "Run the Fortune Client example now.")
173 .arg(ipAddress).arg(tcpServer->serverPort()));
174//! [1]
175}
176
177//! [4]
178void Server::sendFortune()
179{
180//! [5]
181 QByteArray block;
182 QDataStream out(&block, QIODevice::WriteOnly);
183 out.setVersion(QDataStream::Qt_5_10);
184
185 out << fortunes[QRandomGenerator::bounded(fortunes.size())];
186//! [4] //! [7]
187
188 QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
189 connect(clientConnection, &QAbstractSocket::disconnected,
190 clientConnection, &QObject::deleteLater);
191//! [7] //! [8]
192
193 clientConnection->write(block);
194 clientConnection->disconnectFromHost();
195//! [5]
196}
197//! [8]
198