PDA

View Full Version : High performance Http Server



niko
11th December 2009, 08:45
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



#include <QCoreApplication>
#include <QTcpServer>
#include <QThreadPool>
#include <QDateTime>
#include <QTcpSocket>
#include <QStringList>

class Request : public QRunnable
{
public:
Request (int socketDescriptor)
: m_socketDescriptor(socketDescriptor)
{}

virtual void run()
{
QTcpSocket socket;
socket.setSocketDescriptor(m_socketDescriptor);
socket.waitForReadyRead();
QStringList tokens = QString(socket.readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
if (tokens[0] == "GET") {
QTextStream os(&socket);
os.setAutoDetectUnicode(true);
os << "HTTP/1.0 200 Ok\r\n"
"Content-Type: text/html; charset=\"utf-8\"\r\n"
"\r\n"
"<h1>Nothing to see here</h1>\n"
<< QDateTime::currentDateTime().toString() << "\n";
socket.close();
socket.waitForDisconnected();
}
}

private:
int m_socketDescriptor;
};

class HttpDaemon : public QTcpServer
{
public:
HttpDaemon(quint16 port, QObject* parent = 0)
: QTcpServer(parent)
{
if (!listen(QHostAddress::Any, port)) {
qFatal(errorString().toAscii());
}
QThreadPool::globalInstance()->setMaxThreadCount(10);
}

private:
void incomingConnection(int socket)
{
Request *r = new Request(socket);
QThreadPool::globalInstance()->start(r);
}
};

int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
HttpDaemon daemon(8080);
return app.exec();
}

mgoetz
11th December 2009, 09:58
The code looks fine to me.
However, I would not expect to be able to use Qt for a high performance webserver. You'll find a lot of highly optimized webservers on sites like freshmeat. They are using very low level network and IO operations to achieve this. You just can't get to that level of performance with a cross platform library that needs to layer/abstract things.