Skip to content

Commit

Permalink
add threads with router example
Browse files Browse the repository at this point in the history
  • Loading branch information
vinipsmaker committed Oct 20, 2014
1 parent 1dfa076 commit 7e03af8
Show file tree
Hide file tree
Showing 6 changed files with 297 additions and 0 deletions.
57 changes: 57 additions & 0 deletions examples/qmake/threads-with-router-example/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
Copyright (c) 2012 Vinícius dos Santos Oliveira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include <QCoreApplication>
#include <QSharedPointer>

#include <Tufao/HttpFileServer>
#include <Tufao/HttpServerRequestRouter>
#include <Tufao/Headers>

#include "tcpserver.h"

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TcpServer server;

server.run(4, 8080, []() {
QSharedPointer<Tufao::HttpServerRequestRouter>
router(new Tufao::HttpServerRequestRouter);

router->map({QRegularExpression{""},
Tufao::HttpFileServer::handler("public")});

return [router](Tufao::HttpServerRequest &request,
Tufao::HttpServerResponse &response) {
if (!router->handleRequest(request, response)) {
response.writeHead(Tufao::HttpResponseStatus::NOT_FOUND);
response.headers().insert("Content-Type", "text/plain");
response.end("Not found\n");
}

return true;
};
});

return a.exec();
}
56 changes: 56 additions & 0 deletions examples/qmake/threads-with-router-example/tcpserver.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
Copyright (c) 2012 Vinícius dos Santos Oliveira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "tcpserver.h"
#include "worker.h"

#include <QThread>

using namespace Tufao;

TcpServer::TcpServer(QObject *parent) :
QTcpServer(parent),
i(0)
{
}

void TcpServer::run(int threadsNumber, int port, Factory factory)
{
workers.reserve(threadsNumber);
for (int i = 0;i != threadsNumber;++i) {
Worker *worker = new Worker;
QThread *workerThread = new QThread(this);

worker->moveToThread(workerThread);
workerThread->start();

worker->setFactory(factory);

workers.push_back(worker);
}
listen(QHostAddress::Any, port);
}

void TcpServer::incomingConnection(qintptr handle)
{
workers[(i++) % workers.size()]->addConnection(handle);
}
62 changes: 62 additions & 0 deletions examples/qmake/threads-with-router-example/tcpserver.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
Copyright (c) 2012 Vinícius dos Santos Oliveira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <functional>

#include <QTcpServer>
#include <QVector>

class Worker;

namespace Tufao {
class HttpServerRequest;
class HttpServerResponse;
} // namespace Tufao

class TcpServer : public QTcpServer
{
Q_OBJECT
public:
typedef std::function<void(Tufao::HttpServerRequest&,
Tufao::HttpServerResponse&)> Handler;
typedef std::function<Handler()> Factory;

explicit TcpServer(QObject *parent = 0);

void run(int threadsNumber, int port, Factory factory);

signals:
void initReady();
void newConnection(int socketDescriptor);

protected:
void incomingConnection(qintptr handle);

private:
QVector<Worker*> workers;
int i;
};

#endif // TCPSERVER_H
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
TARGET = threads-with-router-example
TEMPLATE = app

CONFIG += C++11 TUFAO1
QT -= gui

SOURCES += main.cpp \
tcpserver.cpp \
worker.cpp

HEADERS += tcpserver.h \
worker.h
76 changes: 76 additions & 0 deletions examples/qmake/threads-with-router-example/worker.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include "worker.h"

#include <QtNetwork/QTcpSocket>

#include <Tufao/HttpServerRequest>
#include <Tufao/Headers>

using namespace Tufao;

Worker::Worker()
{
connect(this, SIGNAL(initReady()), this, SLOT(init()),
Qt::QueuedConnection);
connect(this, &Worker::newConnection/*SIGNAL(newConnection(qintptr))*/,
this, &Worker::onNewConnection/*SLOT(onNewConnection(qintptr))*/,
Qt::QueuedConnection);
}

void Worker::setFactory(TcpServer::Factory factory)
{
factoryMutex.lock();
this->factory = factory;
factoryMutex.unlock();
emit initReady();
}

void Worker::addConnection(qintptr socketDescriptor)
{
emit newConnection(socketDescriptor);
}

void Worker::init()
{
factoryMutex.lock();
handler = factory();
factoryMutex.unlock();
}

void Worker::onNewConnection(qintptr socketDescriptor)
{
QTcpSocket *socket = new QTcpSocket(this);
if (!socket->setSocketDescriptor(socketDescriptor)) {
delete socket;
return;
}

HttpServerRequest *handle = new HttpServerRequest(*socket, this);

connect(handle, SIGNAL(ready()), this, SLOT(onRequestReady()));
connect(handle, SIGNAL(upgrade()), this, SLOT(onUpgrade()));
connect(socket, SIGNAL(disconnected()), handle, SLOT(deleteLater()));
connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
}

void Worker::onRequestReady()
{
HttpServerRequest *request = qobject_cast<HttpServerRequest *>(sender());

QAbstractSocket &socket = request->socket();
HttpServerResponse *response
= new HttpServerResponse(socket, request->responseOptions(), this);

connect(&socket, SIGNAL(disconnected()), response, SLOT(deleteLater()));
connect(response, SIGNAL(finished()), response, SLOT(deleteLater()));

if (request->headers().contains("Expect", "100-continue"))
response->writeContinue();

handler(*request, *response);
}

void Worker::onUpgrade()
{
HttpServerRequest *request = qobject_cast<HttpServerRequest *>(sender());
delete request;
}
34 changes: 34 additions & 0 deletions examples/qmake/threads-with-router-example/worker.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QMutex>

#include "tcpserver.h"

class Worker : public QObject
{
Q_OBJECT
public:
Worker();

void setFactory(TcpServer::Factory factory);
void addConnection(qintptr socketDescriptor);

signals:
void newConnection(qintptr socketDescriptor);
void initReady();

private slots:
void init();
void onNewConnection(qintptr socketDescriptor);
void onRequestReady();
void onUpgrade();

private:
TcpServer::Factory factory;
QMutex factoryMutex;
TcpServer::Handler handler;
};

#endif // WORKER_H

0 comments on commit 7e03af8

Please sign in to comment.