SVN checkout 11/12/2010
[monav:monav.git] / routingdaemon / qtservice-2.6_1-opensource / doc / html / qtservice-example-server.html
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <!DOCTYPE html
3     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 <!-- qtservice-2.6_1-opensource/examples/server/server.qdoc -->
6 <head>
7   <title>A simple HTTP Server</title>
8   <link href="classic.css" rel="stylesheet" type="text/css" />
9 </head>
10 <body>
11 <table border="0" cellpadding="0" cellspacing="0" width="100%">
12 <tr>
13 <td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
14 <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
15 </tr></table><h1 class="title">A simple HTTP Server<br /><span class="subtitle"></span>
16 </h1>
17 <p>It is a very simple implementation of a HTTP daemon that listens on chosen port (defaultly 8080) and sends back a simple HTML page back for every GET request it gets. After sending the page, it closes the connection.</p>
18 <pre><span class="comment"> // HttpDaemon is the the class that implements the simple HTTP server.</span>
19  class HttpDaemon : public QTcpServer
20  {
21      Q_OBJECT
22  public:
23      HttpDaemon(quint16 port, QObject* parent = 0)
24          : QTcpServer(parent), disabled(false)
25      {
26          listen(QHostAddress::Any, port);
27      }
28
29      void incomingConnection(int socket)
30      {
31          if (disabled)
32              return;
33
34          <span class="comment">// When a new client connects, the server constructs a QTcpSocket and all</span>
35          <span class="comment">// communication with the client is done over this QTcpSocket. QTcpSocket</span>
36          <span class="comment">// works asynchronously, this means that all the communication is done</span>
37          <span class="comment">// in the two slots readClient() and discardClient().</span>
38          QTcpSocket* s = new QTcpSocket(this);
39          connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
40          connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
41          s-&gt;setSocketDescriptor(socket);
42
43          QtServiceBase::instance()-&gt;logMessage(&quot;New Connection&quot;);
44      }
45
46      void pause()
47      {
48          disabled = true;
49      }
50
51      void resume()
52      {
53          disabled = false;
54      }
55
56  private slots:
57      void readClient()
58      {
59          if (disabled)
60              return;
61
62          <span class="comment">// This slot is called when the client sent data to the server. The</span>
63          <span class="comment">// server looks if it was a get request and sends a very simple HTML</span>
64          <span class="comment">// document back.</span>
65          QTcpSocket* socket = (QTcpSocket*)sender();
66          if (socket-&gt;canReadLine()) {
67              QStringList tokens = QString(socket-&gt;readLine()).split(QRegExp(&quot;[ \r\n][ \r\n]*&quot;));
68              if (tokens[0] == &quot;GET&quot;) {
69                  QTextStream os(socket);
70                  os.setAutoDetectUnicode(true);
71                  os &lt;&lt; &quot;HTTP/1.0 200 Ok\r\n&quot;
72                      &quot;Content-Type: text/html; charset=\&quot;utf-8\&quot;\r\n&quot;
73                      &quot;\r\n&quot;
74                      &quot;&lt;h1&gt;Nothing to see here&lt;/h1&gt;\n&quot;
75                      &lt;&lt; QDateTime::currentDateTime().toString() &lt;&lt; &quot;\n&quot;;
76                  socket-&gt;close();
77
78                  QtServiceBase::instance()-&gt;logMessage(&quot;Wrote to client&quot;);
79
80                  if (socket-&gt;state() == QTcpSocket::UnconnectedState) {
81                      delete socket;
82                      QtServiceBase::instance()-&gt;logMessage(&quot;Connection closed&quot;);
83                  }
84              }
85          }
86      }
87      void discardClient()
88      {
89          QTcpSocket* socket = (QTcpSocket*)sender();
90          socket-&gt;deleteLater();
91
92          QtServiceBase::instance()-&gt;logMessage(&quot;Connection closed&quot;);
93      }
94
95  private:
96      bool disabled;
97  };</pre>
98 <p>The server implementation uses the <a href="qtservicebase.html#logMessage">QtService::logMessage</a>() function to send messages and status reports to the system event log. The server also supports a paused state in which case incoming requests are ignored.</p>
99 <p>The <tt>HttpService</tt> class subclasses <a href="qtservice.html">QtService</a> to implement the service functionality.</p>
100 <pre> class HttpService : public QtService&lt;QCoreApplication&gt;
101  {
102  public:
103      HttpService(int argc, char **argv)
104          : QtService&lt;QCoreApplication&gt;(argc, argv, &quot;Qt HTTP Daemon&quot;)
105      {
106          setServiceDescription(&quot;A dummy HTTP service implemented with Qt&quot;);
107          setServiceFlags(QtServiceBase::CanBeSuspended);
108      }</pre>
109 <p>The constructor calls the <a href="qtservice.html">QtService</a> constructor instantiated with <a href="http://qt.nokia.com/doc/4.5/qcoreapplication.html">QCoreApplication</a> since our service will not use GUI. The first two parameters of our constructor are passed to <a href="qtservice.html">QtService</a>. The last parameter, &quot;Qt HTTP Daemon&quot;, is the name of the service.</p>
110 <pre> protected:
111      void start()
112      {
113          QCoreApplication *app = application();
114
115          quint16 port = (app-&gt;argc() &gt; 1) ?
116                  QString::fromLocal8Bit(app-&gt;argv()[1]).toUShort() : 8080;
117          daemon = new HttpDaemon(port, app);
118
119          if (!daemon-&gt;isListening()) {
120              logMessage(QString(&quot;Failed to bind to port %1&quot;).arg(daemon-&gt;serverPort()), QtServiceBase::Error);
121              app-&gt;quit();
122          }
123      }</pre>
124 <p>The implementation of <tt>start()</tt> first checks if the user passed a port number. If yes that port is used by server to listen on. Otherwise default 8080 port is used. Then creates an instance of the HTTP server using operator new, passing the application object as the parent to ensure that the object gets destroyed.</p>
125 <pre>     void pause()
126      {
127          daemon-&gt;pause();
128      }
129
130      void resume()
131      {
132          daemon-&gt;resume();
133      }
134
135  private:
136      HttpDaemon *daemon;
137  };</pre>
138 <p>The implementations of pause() and resume() forward the request to the server object.</p>
139 <pre> #include &quot;main.moc&quot;
140
141  int main(int argc, char **argv)
142  {
143  #if !defined(Q_WS_WIN)
144      <span class="comment">// QtService stores service settings in SystemScope, which normally require root privileges.</span>
145      <span class="comment">// To allow testing this example as non-root, we change the directory of the SystemScope settings file.</span>
146      QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
147      qWarning(&quot;(Example uses dummy settings file: %s/QtSoftware.conf)&quot;, QDir::tempPath().toLatin1().constData());
148  #endif
149      HttpService service(argc, argv);
150      return service.exec();
151  }</pre>
152 <p>The main entry point function creates the service object and uses the <tt>exec()</tt> function to execute the service.</p>
153 <p /><address><hr /><div align="center">
154 <table width="100%" cellspacing="0" border="0"><tr class="address">
155 <td width="30%" align="left">Copyright &copy; 2009 Nokia Corporation and/or its subsidiary(-ies)</td>
156 <td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
157 <td width="30%" align="right"><div align="right">Qt Solutions</div></td>
158 </tr></table></div></address></body>
159 </html>