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 initServer();
65
66 //! [2]
67 fortunes << tr(s: "You've been leading a dog's life. Stay off the furniture.")
68 << tr(s: "You've got to think about tomorrow.")
69 << tr(s: "You will be surprised by a loud noise.")
70 << tr(s: "You will feel hungry again in another hour.")
71 << tr(s: "You might have mail.")
72 << tr(s: "You cannot kill time without injuring eternity.")
73 << tr(s: "Computers are not intelligent. They only think they are.");
74 //! [2]
75 auto quitButton = new QPushButton(tr(s: "Quit"));
76 quitButton->setAutoDefault(false);
77 connect(sender: quitButton, signal: &QAbstractButton::clicked, receiver: this, slot: &QWidget::close);
78 //! [3]
79 connect(sender: tcpServer, signal: &QTcpServer::newConnection, receiver: this, slot: &Server::sendFortune);
80 //! [3]
81
82 auto buttonLayout = new QHBoxLayout;
83 buttonLayout->addStretch(stretch: 1);
84 buttonLayout->addWidget(quitButton);
85 buttonLayout->addStretch(stretch: 1);
86
87 QVBoxLayout *mainLayout = nullptr;
88 if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) {
89 auto outerVerticalLayout = new QVBoxLayout(this);
90 outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
91 auto outerHorizontalLayout = new QHBoxLayout;
92 outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
93 auto groupBox = new QGroupBox(QGuiApplication::applicationDisplayName());
94 mainLayout = new QVBoxLayout(groupBox);
95 outerHorizontalLayout->addWidget(groupBox);
96 outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
97 outerVerticalLayout->addLayout(layout: outerHorizontalLayout);
98 outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
99 } else {
100 mainLayout = new QVBoxLayout(this);
101 }
102
103 mainLayout->addWidget(statusLabel);
104 mainLayout->addLayout(layout: buttonLayout);
105
106 setWindowTitle(QGuiApplication::applicationDisplayName());
107}
108
109void Server::initServer()
110{
111//! [0] //! [1]
112 tcpServer = new QTcpServer(this);
113 if (!tcpServer->listen()) {
114 QMessageBox::critical(parent: this, title: tr(s: "Fortune Server"),
115 text: tr(s: "Unable to start the server: %1.")
116 .arg(a: tcpServer->errorString()));
117 close();
118 return;
119 }
120//! [0]
121 QString ipAddress;
122 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
123 // use the first non-localhost IPv4 address
124 for (int i = 0; i < ipAddressesList.size(); ++i) {
125 if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
126 ipAddressesList.at(i).toIPv4Address()) {
127 ipAddress = ipAddressesList.at(i).toString();
128 break;
129 }
130 }
131 // if we did not find one, use IPv4 localhost
132 if (ipAddress.isEmpty())
133 ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
134 statusLabel->setText(tr(s: "The server is running on\n\nIP: %1\nport: %2\n\n"
135 "Run the Fortune Client example now.")
136 .arg(a: ipAddress).arg(a: tcpServer->serverPort()));
137//! [1]
138}
139
140//! [4]
141void Server::sendFortune()
142{
143//! [5]
144 QByteArray block;
145 QDataStream out(&block, QIODevice::WriteOnly);
146 out.setVersion(QDataStream::Qt_5_10);
147
148 out << fortunes[QRandomGenerator::global()->bounded(highest: fortunes.size())];
149//! [4] //! [7]
150
151 QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
152 connect(sender: clientConnection, signal: &QAbstractSocket::disconnected,
153 receiver: clientConnection, slot: &QObject::deleteLater);
154//! [7] //! [8]
155
156 clientConnection->write(data: block);
157 clientConnection->disconnectFromHost();
158//! [5]
159}
160//! [8]
161

source code of qtbase/examples/network/fortuneserver/server.cpp