PageRenderTime 45ms CodeModel.GetById 7ms app.highlight 33ms RepoModel.GetById 1ms app.codeStats 0ms

/vp_plugins/qtservice-2.6_1-opensource/examples/server/main.cpp

http://cupsfilter.googlecode.com/
C++ | 190 lines | 112 code | 23 blank | 55 comment | 8 complexity | ef4c1dd3b2420d2180518e68c72d8b76 MD5 | raw file
  1/****************************************************************************
  2** 
  3** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
  4** All rights reserved.
  5** Contact: Nokia Corporation (qt-info@nokia.com)
  6** 
  7** This file is part of a Qt Solutions component.
  8**
  9** Commercial Usage  
 10** Licensees holding valid Qt Commercial licenses may use this file in
 11** accordance with the Qt Solutions Commercial License Agreement provided
 12** with the Software or, alternatively, in accordance with the terms
 13** contained in a written agreement between you and Nokia.
 14** 
 15** GNU Lesser General Public License Usage
 16** Alternatively, this file may be used under the terms of the GNU Lesser
 17** General Public License version 2.1 as published by the Free Software
 18** Foundation and appearing in the file LICENSE.LGPL included in the
 19** packaging of this file.  Please review the following information to
 20** ensure the GNU Lesser General Public License version 2.1 requirements
 21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 22** 
 23** In addition, as a special exception, Nokia gives you certain
 24** additional rights. These rights are described in the Nokia Qt LGPL
 25** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
 26** package.
 27** 
 28** GNU General Public License Usage 
 29** Alternatively, this file may be used under the terms of the GNU
 30** General Public License version 3.0 as published by the Free Software
 31** Foundation and appearing in the file LICENSE.GPL included in the
 32** packaging of this file.  Please review the following information to
 33** ensure the GNU General Public License version 3.0 requirements will be
 34** met: http://www.gnu.org/copyleft/gpl.html.
 35** 
 36** Please note Third Party Software included with Qt Solutions may impose
 37** additional restrictions and it is the user's responsibility to ensure
 38** that they have met the licensing requirements of the GPL, LGPL, or Qt
 39** Solutions Commercial license and the relevant license of the Third
 40** Party Software they are using.
 41** 
 42** If you are unsure which license is appropriate for your use, please
 43** contact Nokia at qt-info@nokia.com.
 44** 
 45****************************************************************************/
 46
 47#include <QtCore/QCoreApplication>
 48#include <QtNetwork/QTcpServer>
 49#include <QtNetwork/QTcpSocket>
 50#include <QtCore/QTextStream>
 51#include <QtCore/QDateTime>
 52#include <QtCore/QStringList>
 53#include <QtCore/QDir>
 54#include <QtCore/QSettings>
 55
 56#include "qtservice.h"
 57
 58// HttpDaemon is the the class that implements the simple HTTP server.
 59class HttpDaemon : public QTcpServer
 60{
 61    Q_OBJECT
 62public:
 63    HttpDaemon(quint16 port, QObject* parent = 0)
 64        : QTcpServer(parent), disabled(false)
 65    {
 66        listen(QHostAddress::Any, port);
 67    }
 68
 69    void incomingConnection(int socket)
 70    {
 71        if (disabled)
 72            return;
 73
 74        // When a new client connects, the server constructs a QTcpSocket and all
 75        // communication with the client is done over this QTcpSocket. QTcpSocket
 76        // works asynchronously, this means that all the communication is done
 77        // in the two slots readClient() and discardClient().
 78        QTcpSocket* s = new QTcpSocket(this);
 79        connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
 80        connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
 81        s->setSocketDescriptor(socket);
 82
 83        QtServiceBase::instance()->logMessage("New Connection");
 84    }
 85
 86    void pause()
 87    {
 88        disabled = true;
 89    }
 90
 91    void resume()
 92    {
 93        disabled = false;
 94    }
 95
 96private slots:
 97    void readClient()
 98    {
 99        if (disabled)
100            return;
101
102        // This slot is called when the client sent data to the server. The
103        // server looks if it was a get request and sends a very simple HTML
104        // document back.
105        QTcpSocket* socket = (QTcpSocket*)sender();
106        if (socket->canReadLine()) {
107            QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
108            if (tokens[0] == "GET") {
109                QTextStream os(socket);
110                os.setAutoDetectUnicode(true);
111                os << "HTTP/1.0 200 Ok\r\n"
112                    "Content-Type: text/html; charset=\"utf-8\"\r\n"
113                    "\r\n"
114                    "<h1>Nothing to see here</h1>\n"
115                    << QDateTime::currentDateTime().toString() << "\n";
116                socket->close();
117
118                QtServiceBase::instance()->logMessage("Wrote to client");
119
120                if (socket->state() == QTcpSocket::UnconnectedState) {
121                    delete socket;
122                    QtServiceBase::instance()->logMessage("Connection closed");
123                }
124            }
125        }
126    }
127    void discardClient()
128    {
129        QTcpSocket* socket = (QTcpSocket*)sender();
130        socket->deleteLater();
131
132        QtServiceBase::instance()->logMessage("Connection closed");
133    }
134
135private:
136    bool disabled;
137};
138
139class HttpService : public QtService<QCoreApplication>
140{
141public:
142    HttpService(int argc, char **argv)
143	: QtService<QCoreApplication>(argc, argv, "Qt HTTP Daemon")
144    {
145        setServiceDescription("A dummy HTTP service implemented with Qt");
146        setServiceFlags(QtServiceBase::CanBeSuspended);
147    }
148
149protected:
150    void start()
151    {
152        QCoreApplication *app = application();
153
154        quint16 port = (app->argc() > 1) ?
155                QString::fromLocal8Bit(app->argv()[1]).toUShort() : 8080;
156        daemon = new HttpDaemon(port, app);
157
158        if (!daemon->isListening()) {
159            logMessage(QString("Failed to bind to port %1").arg(daemon->serverPort()), QtServiceBase::Error);
160            app->quit();
161        }
162    }
163
164    void pause()
165    {
166	daemon->pause();
167    }
168
169    void resume()
170    {
171	daemon->resume();
172    }
173
174private:
175    HttpDaemon *daemon;
176};
177
178#include "main.moc"
179
180int main(int argc, char **argv)
181{
182#if !defined(Q_WS_WIN)
183    // QtService stores service settings in SystemScope, which normally require root privileges.
184    // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
185    QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
186    qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
187#endif
188    HttpService service(argc, argv);
189    return service.exec();
190}