Hi,

I want to write a high performance http server. The attached code is what I came up with so far.
Benchmarking showed that it serves just a little more than an apache http server - while apache does a lot more.

Any suggestions on how I could improve this?

thanks,
Niko

Qt Code:
  1. #include <QCoreApplication>
  2. #include <QTcpServer>
  3. #include <QThreadPool>
  4. #include <QDateTime>
  5. #include <QTcpSocket>
  6. #include <QStringList>
  7.  
  8. class Request : public QRunnable
  9. {
  10. public:
  11. Request (int socketDescriptor)
  12. : m_socketDescriptor(socketDescriptor)
  13. {}
  14.  
  15. virtual void run()
  16. {
  17. QTcpSocket socket;
  18. socket.setSocketDescriptor(m_socketDescriptor);
  19. socket.waitForReadyRead();
  20. QStringList tokens = QString(socket.readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
  21. if (tokens[0] == "GET") {
  22. QTextStream os(&socket);
  23. os.setAutoDetectUnicode(true);
  24. os << "HTTP/1.0 200 Ok\r\n"
  25. "Content-Type: text/html; charset=\"utf-8\"\r\n"
  26. "\r\n"
  27. "<h1>Nothing to see here</h1>\n"
  28. << QDateTime::currentDateTime().toString() << "\n";
  29. socket.close();
  30. socket.waitForDisconnected();
  31. }
  32. }
  33.  
  34. private:
  35. int m_socketDescriptor;
  36. };
  37.  
  38. class HttpDaemon : public QTcpServer
  39. {
  40. public:
  41. HttpDaemon(quint16 port, QObject* parent = 0)
  42. : QTcpServer(parent)
  43. {
  44. if (!listen(QHostAddress::Any, port)) {
  45. qFatal(errorString().toAscii());
  46. }
  47. QThreadPool::globalInstance()->setMaxThreadCount(10);
  48. }
  49.  
  50. private:
  51. void incomingConnection(int socket)
  52. {
  53. Request *r = new Request(socket);
  54. QThreadPool::globalInstance()->start(r);
  55. }
  56. };
  57.  
  58. int main(int argc, char** argv)
  59. {
  60. QCoreApplication app(argc, argv);
  61. HttpDaemon daemon(8080);
  62. return app.exec();
  63. }
To copy to clipboard, switch view to plain text mode