source: trunk/examples/network/fortuneserver/server.cpp@ 855

Last change on this file since 855 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 6.7 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:BSD$
10** You may use this file under the terms of the BSD license as follows:
11**
12** "Redistribution and use in source and binary forms, with or without
13** modification, are permitted provided that the following conditions are
14** met:
15** * Redistributions of source code must retain the above copyright
16** notice, this list of conditions and the following disclaimer.
17** * Redistributions in binary form must reproduce the above copyright
18** notice, this list of conditions and the following disclaimer in
19** the documentation and/or other materials provided with the
20** distribution.
21** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
22** the names of its contributors may be used to endorse or promote
23** products derived from this software without specific prior written
24** permission.
25**
26** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#include <QtGui>
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("Trolltech"));
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("Trolltech"));
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]
Note: See TracBrowser for help on using the repository browser.