1/****************************************************************************
2**
3** Copyright (C) 2016 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
54#include <stdlib.h>
55
56#include "server.h"
57
58Server::Server(QWidget *parent)
59 : QDialog(parent)
60 , statusLabel(new QLabel)
61 , tcpServer(Q_NULLPTR)
62 , networkSession(0)
63{
64 setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
65 statusLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
66
67 QNetworkConfigurationManager manager;
68 if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
69 // Get saved network configuration
70 QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
71 settings.beginGroup(QLatin1String("QtNetwork"));
72 const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
73 settings.endGroup();
74
75 // If the saved network configuration is not currently discovered use the system default
76 QNetworkConfiguration config = manager.configurationFromIdentifier(id);
77 if ((config.state() & QNetworkConfiguration::Discovered) !=
78 QNetworkConfiguration::Discovered) {
79 config = manager.defaultConfiguration();
80 }
81
82 networkSession = new QNetworkSession(config, this);
83 connect(networkSession, &QNetworkSession::opened, this, &Server::sessionOpened);
84
85 statusLabel->setText(tr("Opening network session."));
86 networkSession->open();
87 } else {
88 sessionOpened();
89 }
90
91 //! [2]
92 fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
93 << tr("You've got to think about tomorrow.")
94 << tr("You will be surprised by a loud noise.")
95 << tr("You will feel hungry again in another hour.")
96 << tr("You might have mail.")
97 << tr("You cannot kill time without injuring eternity.")
98 << tr("Computers are not intelligent. They only think they are.");
99 //! [2]
100 QPushButton *quitButton = new QPushButton(tr("Quit"));
101 quitButton->setAutoDefault(false);
102 connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close);
103 //! [3]
104 connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendFortune);
105 //! [3]
106
107 QHBoxLayout *buttonLayout = new QHBoxLayout;
108 buttonLayout->addStretch(1);
109 buttonLayout->addWidget(quitButton);
110 buttonLayout->addStretch(1);
111
112 QVBoxLayout *mainLayout = Q_NULLPTR;
113 if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) {
114 QVBoxLayout *outerVerticalLayout = new QVBoxLayout(this);
115 outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
116 QHBoxLayout *outerHorizontalLayout = new QHBoxLayout;
117 outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
118 QGroupBox *groupBox = new QGroupBox(QGuiApplication::applicationDisplayName());
119 mainLayout = new QVBoxLayout(groupBox);
120 outerHorizontalLayout->addWidget(groupBox);
121 outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
122 outerVerticalLayout->addLayout(outerHorizontalLayout);
123 outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
124 } else {
125 mainLayout = new QVBoxLayout(this);
126 }
127
128 mainLayout->addWidget(statusLabel);
129 mainLayout->addLayout(buttonLayout);
130
131 setWindowTitle(QGuiApplication::applicationDisplayName());
132}
133
134void Server::sessionOpened()
135{
136 // Save the used configuration
137 if (networkSession) {
138 QNetworkConfiguration config = networkSession->configuration();
139 QString id;
140 if (config.type() == QNetworkConfiguration::UserChoice)
141 id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
142 else
143 id = config.identifier();
144
145 QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
146 settings.beginGroup(QLatin1String("QtNetwork"));
147 settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
148 settings.endGroup();
149 }
150
151//! [0] //! [1]
152 tcpServer = new QTcpServer(this);
153 if (!tcpServer->listen()) {
154 QMessageBox::critical(this, tr("Fortune Server"),
155 tr("Unable to start the server: %1.")
156 .arg(tcpServer->errorString()));
157 close();
158 return;
159 }
160//! [0]
161 QString ipAddress;
162 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
163 // use the first non-localhost IPv4 address
164 for (int i = 0; i < ipAddressesList.size(); ++i) {
165 if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
166 ipAddressesList.at(i).toIPv4Address()) {
167 ipAddress = ipAddressesList.at(i).toString();
168 break;
169 }
170 }
171 // if we did not find one, use IPv4 localhost
172 if (ipAddress.isEmpty())
173 ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
174 statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
175 "Run the Fortune Client example now.")
176 .arg(ipAddress).arg(tcpServer->serverPort()));
177//! [1]
178}
179
180//! [4]
181void Server::sendFortune()
182{
183//! [5]
184 QByteArray block;
185 QDataStream out(&block, QIODevice::WriteOnly);
186 out.setVersion(QDataStream::Qt_4_0);
187
188 out << fortunes.at(qrand() % fortunes.size());
189//! [4] //! [7]
190
191 QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
192 connect(clientConnection, &QAbstractSocket::disconnected,
193 clientConnection, &QObject::deleteLater);
194//! [7] //! [8]
195
196 clientConnection->write(block);
197 clientConnection->disconnectFromHost();
198//! [5]
199}
200//! [8]
201