remotegenerator.h.bak 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #ifndef REMOTEGENERATOR_H
  2. #define REMOTEGENERATOR_H
  3. #include <QObject>
  4. #include <QSocket>
  5. #include <QTcpServer>
  6. // HttpDaemon from http://doc.trolltech.com/solutions/3/qtservice/qtservice-example-server.html. Used for prototype purposes.
  7. // HttpDaemon is the the class that implements the simple HTTP server.
  8. class HttpDaemon : public QTcpServer
  9. {
  10. Q_OBJECT
  11. public:
  12. HttpDaemon( QObject* parent=0 ) :
  13. QTcpServer(8080,1,parent), disabled(FALSE)
  14. {
  15. if ( !ok() ) {
  16. qService->reportEvent( "Failed to bind to port 8080", QtService::Error );
  17. exit( 1 );
  18. }
  19. }
  20. void newConnection( int socket )
  21. {
  22. if ( disabled )
  23. return;
  24. // When a new client connects, the server constructs a QSocket and all
  25. // communication with the client is done over this QSocket. QSocket
  26. // works asynchronouslyl, this means that all the communication is done
  27. // in the two slots readClient() and discardClient().
  28. QSocket* s = new QSocket( this );
  29. connect( s, SIGNAL(readyRead()), this, SLOT(readClient()) );
  30. connect( s, SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) );
  31. s->setSocket( socket );
  32. qService->reportEvent( "New Connection" );
  33. }
  34. void pause()
  35. {
  36. disabled = TRUE;
  37. }
  38. void resume()
  39. {
  40. disabled = FALSE;
  41. }
  42. private slots:
  43. void readClient()
  44. {
  45. if ( disabled )
  46. return;
  47. // This slot is called when the client sent data to the server. The
  48. // server looks if it was a get request and sends a very simple HTML
  49. // document back.
  50. QSocket* socket = (QSocket*)sender();
  51. if ( socket->canReadLine() ) {
  52. QStringList tokens = QStringList::split( QRegExp("[ \r\n][ \r\n]*"), socket->readLine() );
  53. if ( tokens[0] == "GET" ) {
  54. QTextStream os( socket );
  55. os.setEncoding( QTextStream::UnicodeUTF8 );
  56. os << "HTTP/1.0 200 Ok\r\n"
  57. "Content-Type: text/html; charset=\"utf-8\"\r\n"
  58. "\r\n"
  59. "<h1>Nothing to see here</h1>\n";
  60. socket->close();
  61. qService->reportEvent( "Wrote to client" );
  62. }
  63. }
  64. }
  65. void discardClient()
  66. {
  67. QSocket* socket = (QSocket*)sender();
  68. delete socket;
  69. qService->reportEvent( "Connection closed" );
  70. }
  71. private:
  72. bool disabled;
  73. };
  74. class RemoteGenerator : public QObject
  75. {
  76. Q_OBJECT
  77. public:
  78. explicit RemoteGenerator(QObject *parent = 0);
  79. signals:
  80. public slots:
  81. };
  82. #endif // REMOTEGENERATOR_H