1/****************************************************************************
2**
3** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4** Contact: http://www.qt-project.org/legal
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 Digia Plc and its Subsidiary(-ies) nor the names
21** of its 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), tcpServer(0), networkSession(0)
50{
51 statusLabel = new QLabel;
52 quitButton = new QPushButton(tr("Quit"));
53 quitButton->setAutoDefault(false);
54
55 QNetworkConfigurationManager manager;
56 if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
57 // Get saved network configuration
58 QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
59 settings.beginGroup(QLatin1String("QtNetwork"));
60 const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
61 settings.endGroup();
62
63 // If the saved network configuration is not currently discovered use the system default
64 QNetworkConfiguration config = manager.configurationFromIdentifier(id);
65 if ((config.state() & QNetworkConfiguration::Discovered) !=
66 QNetworkConfiguration::Discovered) {
67 config = manager.defaultConfiguration();
68 }
69
70 networkSession = new QNetworkSession(config, this);
71 connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
72
73 statusLabel->setText(tr("Opening network session."));
74 networkSession->open();
75 } else {
76 sessionOpened();
77 }
78
79 //! [2]
80 fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
81 << tr("You've got to think about tomorrow.")
82 << tr("You will be surprised by a loud noise.")
83 << tr("You will feel hungry again in another hour.")
84 << tr("You might have mail.")
85 << tr("You cannot kill time without injuring eternity.")
86 << tr("Computers are not intelligent. They only think they are.");
87 //! [2]
88
89 connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
90 //! [3]
91 connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));
92 //! [3]
93
94 QHBoxLayout *buttonLayout = new QHBoxLayout;
95 buttonLayout->addStretch(1);
96 buttonLayout->addWidget(quitButton);
97 buttonLayout->addStretch(1);
98
99 QVBoxLayout *mainLayout = new QVBoxLayout;
100 mainLayout->addWidget(statusLabel);
101 mainLayout->addLayout(buttonLayout);
102 setLayout(mainLayout);
103
104 setWindowTitle(tr("Fortune Server"));
105}
106
107void Server::sessionOpened()
108{
109 // Save the used configuration
110 if (networkSession) {
111 QNetworkConfiguration config = networkSession->configuration();
112 QString id;
113 if (config.type() == QNetworkConfiguration::UserChoice)
114 id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
115 else
116 id = config.identifier();
117
118 QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
119 settings.beginGroup(QLatin1String("QtNetwork"));
120 settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
121 settings.endGroup();
122 }
123
124//! [0] //! [1]
125 tcpServer = new QTcpServer(this);
126 if (!tcpServer->listen()) {
127 QMessageBox::critical(this, tr("Fortune Server"),
128 tr("Unable to start the server: %1.")
129 .arg(tcpServer->errorString()));
130 close();
131 return;
132 }
133//! [0]
134 QString ipAddress;
135 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
136 // use the first non-localhost IPv4 address
137 for (int i = 0; i < ipAddressesList.size(); ++i) {
138 if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
139 ipAddressesList.at(i).toIPv4Address()) {
140 ipAddress = ipAddressesList.at(i).toString();
141 break;
142 }
143 }
144 // if we did not find one, use IPv4 localhost
145 if (ipAddress.isEmpty())
146 ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
147 statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
148 "Run the Fortune Client example now.")
149 .arg(ipAddress).arg(tcpServer->serverPort()));
150//! [1]
151}
152
153//! [4]
154void Server::sendFortune()
155{
156//! [5]
157 QByteArray block;
158 QDataStream out(&block, QIODevice::WriteOnly);
159 out.setVersion(QDataStream::Qt_4_0);
160//! [4] //! [6]
161 out << (quint16)0;
162 out << fortunes.at(qrand() % fortunes.size());
163 out.device()->seek(0);
164 out << (quint16)(block.size() - sizeof(quint16));
165//! [6] //! [7]
166
167 QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
168 connect(clientConnection, SIGNAL(disconnected()),
169 clientConnection, SLOT(deleteLater()));
170//! [7] //! [8]
171
172 clientConnection->write(block);
173 clientConnection->disconnectFromHost();
174//! [5]
175}
176//! [8]
177