Here is a very simple HTTP web server that will update the number of seconds, each second, since a connection was made on the web browser.
It also displays the data sent by the web browser on the screen.
The program is set to use port 8080
e.g 127.0.0.1:8080
#-------------- Project file webServer3.pro -------
QT += core
QT += network
QT -= gui
TARGET = webServer3
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
HEADERS += \
myhttpserver.h
/*------------------header file myhttpserver.h --------------*/
#ifndef MYHTTPSERVER
#define MYHTTPSERVER
#include
#include
#include
#include
#include
#include
#include
class myHTTPserver : public QObject
{
Q_OBJECT
public:
explicit myHTTPserver(QObject *parent = 0);
~myHTTPserver();
QTcpSocket *socket ;
public slots:
void myConnection();
private:
qint64 bytesAvailable() const;
QTcpServer *server;
signals:
};
/*------------------------main.cpp -------------------------*/
#include "myhttpserver.h"
using namespace std;
void delayms( int millisecondsToWait );
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
myHTTPserver server;
return a.exec();
}
myHTTPserver::myHTTPserver(QObject *parent) : QObject(parent)
{
server = new QTcpServer(this);
// waiting for the web brower to make contact,this will emit signal
connect(server, SIGNAL(newConnection()),this, SLOT(myConnection()));
if(!server->listen(QHostAddress::Any,8080))cout<< "\nWeb server could not start";
else cout<<"\nWeb server is waiting for a connection on port 8080";
}
void myHTTPserver::myConnection()
{
static qint16 count; //count number to be displayed on web browser
socket = server->nextPendingConnection();
while(!(socket->waitForReadyRead(100))); //waiting for data to be read from web browser
char webBrowerRXData[1000];
int sv=socket->read(webBrowerRXData,1000);
cout<<"\nreading web browser data=\n";
for(int i=0;iwrite("HTTP/1.1 200 OK\r\n"); // \r needs to be before \n
socket->write("Content-Type: text/html\r\n");
socket->write("Connection: close\r\n");
socket->write("Refresh: 1\r\n\r\n"); //refreshes web browser every second. Require two \r\n.
socket->write("\r\n");
socket->write("Number of seconds since connected.. ");
QByteArray str;
str.setNum(count++); //convert int to string
socket->write(str);
socket->write(" \n\n");
socket->flush();
connect(socket, SIGNAL(disconnected()),socket, SLOT(deleteLater()));
socket->disconnectFromHost();
}
myHTTPserver::~myHTTPserver()
{
socket->close();
}