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()
{
socket.setSocketDescriptor(m_socketDescriptor);
socket.waitForReadyRead();
if (tokens[0] == "GET") {
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;
};
{
public:
HttpDaemon
(quint16 port,
QObject* parent
= 0) {
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)
{
HttpDaemon daemon(8080);
return app.exec();
}
#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();
}
To copy to clipboard, switch view to plain text mode
Bookmarks