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