Merge pull request #5609 from murillodigital/master

Better handling of socket binding
This commit is contained in:
Brad Davis 2015-08-21 00:22:19 -07:00
commit f6f189c4b8
2 changed files with 36 additions and 7 deletions

View file

@ -9,6 +9,7 @@
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
@ -19,16 +20,19 @@
#include "EmbeddedWebserverLogging.h"
#include "HTTPManager.h"
const int SOCKET_ERROR_EXIT_CODE = 2;
const int SOCKET_CHECK_INTERVAL_IN_MS = 30000;
HTTPManager::HTTPManager(quint16 port, const QString& documentRoot, HTTPRequestHandler* requestHandler, QObject* parent) :
QTcpServer(parent),
_documentRoot(documentRoot),
_requestHandler(requestHandler)
_requestHandler(requestHandler),
_port(port)
{
// start listening on the passed port
if (!listen(QHostAddress("0.0.0.0"), port)) {
qCDebug(embeddedwebserver) << "Failed to open HTTP server socket:" << errorString();
return;
}
bindSocket();
_isListeningTimer = new QTimer(this);
connect(_isListeningTimer, &QTimer::timeout, this, &HTTPManager::isTcpServerListening);
_isListeningTimer->start(SOCKET_CHECK_INTERVAL_IN_MS);
}
void HTTPManager::incomingConnection(qintptr socketDescriptor) {
@ -157,3 +161,19 @@ bool HTTPManager::handleHTTPRequest(HTTPConnection* connection, const QUrl& url,
bool HTTPManager::requestHandledByRequestHandler(HTTPConnection* connection, const QUrl& url) {
return _requestHandler && _requestHandler->handleHTTPRequest(connection, url);
}
void HTTPManager::isTcpServerListening() {
if (!isListening()) {
qCWarning(embeddedwebserver) << "Socket on port " << QString::number(_port) << " is no longer listening";
bindSocket();
}
}
bool HTTPManager::bindSocket() {
qCDebug(embeddedwebserver) << "Attempting to bind TCP socket on port " << QString::number(_port);
if (!listen(QHostAddress::Any, _port)) {
qCritical() << "Failed to open HTTP server socket:" << errorString() << " can't continue";
QCoreApplication::exit(SOCKET_ERROR_EXIT_CODE);
}
return true;
}

View file

@ -17,6 +17,7 @@
#define hifi_HTTPManager_h
#include <QtNetwork/QTcpServer>
#include <QtCore/QTimer>
class HTTPConnection;
class HTTPSConnection;
@ -35,14 +36,22 @@ public:
HTTPManager(quint16 port, const QString& documentRoot, HTTPRequestHandler* requestHandler = NULL, QObject* parent = 0);
bool handleHTTPRequest(HTTPConnection* connection, const QUrl& url, bool skipSubHandler = false);
private slots:
void isTcpServerListening();
private:
bool bindSocket();
protected:
/// Accepts all pending connections
virtual void incomingConnection(qintptr socketDescriptor);
virtual bool requestHandledByRequestHandler(HTTPConnection* connection, const QUrl& url);
protected:
QString _documentRoot;
HTTPRequestHandler* _requestHandler;
QTimer* _isListeningTimer;
const quint16 _port;
};
#endif // hifi_HTTPManager_h