HTTP Server implementation

Source: Internet
Author: User

The QT-based Qtcpserver class implements a simple HTTP server tinyhttpd. The code is stored on GitHub.

Qthread and Qtimer settings

When the subclass Qthread, the constructor executes in the old thread, but run () executes in the new thread. If a member variable is accessed from two functions and then accesses the variable from two different threads, you need to check to see if it is safe.

Qtimer cannot be instantiated in one thread, but on another thread start or stop. The method taken is:

QTimer* keep_alive_timer;void Request::run(){    keep_alive_timer = new QTimer();    if (s_keep_alive_enable)    {        keep_alive = s_keep_alive_default;        keep_alive_timeout = s_keep_alive_timeout * 1000;// the wait time        connect(keep_alive_timer,SIGNAL(timeout()),this,SLOT(onTimeout()));        keep_alive_timer->setSingleShot(true);        keep_alive_timer->setInterval(keep_alive_timeout);        keep_alive_timer->start();    }    socket = new QTcpSocket();    if (!socket->setSocketDescriptor(socketDescriptor))        return;    connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()),     Qt::DirectConnection);    connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()),    Qt::DirectConnection);    exec();}
Qt Event Loop mechanism

After the above run () there is an EXEC () function, which goes into the event loop.

The event loop for Qt is asynchronous, and when Qapplication::exec () is called, it enters the event loop. The loop can be simplified as described in the following code:

while ( !app_exit_loop ){   while( !postedEvents ) { processPostedEvents() }   while( !qwsEvnts ){ qwsProcessEvents();   }   while( !postedEvents ) { processPostedEvents() }}

The events in the Qt event queue are processed first until they are empty. The message in the system message queue is processed until it is empty. A new QT event is generated when the system message is processed and needs to be processed again.

QT garbage collection mechanism

There are many places in the program where new objects do not have a delete, which will cause a memory leak.

Not in QT, it implements its own GC mechanism.

All classes that inherit from the Qobject class, if the father is specified at new, the cleanup is when the father is deleted. If a program, all of the Qobject classes are designated fathers, then they will be first-class at the top of the Father cleanup when cleared. We need to explicitly release the orphaned pointer objects that do not have a parent object.

Multi-port monitoring implementation

The configuration file for port is defined so

[httpd]port=1234|1235|1236|1237

Read configuration

bool ok;QString t_port = Settings::instance().value("httpd/port").toString();QStringList port_list = t_port.split("|");for(int i = 0; i < port_list.size(); i++)    {        int port = port_list[i].toInt(&ok,10);        startInstance(port);    }    return true;

Note that listen (Qhostaddress::any, 1234) refers to any IP that is connected to the 1234 port.

Incomingconnection virtual function

It is a virtual function that is called by Qtcpserver when the server receives a connection request. It creates a qtcpsocket at the bottom, sets the socket descriptor and adds the descriptor to the internal list (the internal may use Select for asynchronous read and write data). When overloading this function, you can change the behavior of the server when it receives a connection request, which is equivalent to implementing a hook. This allows the HTTP server to be implemented in this function.

void Server::incomingConnection(int socketDescriptor){    //有新的连接时,代替默认的功能(新建socket)    Request * request = new Request(socketDescriptor);    request->start();}

A visible socket descriptor is passed to the request instance, which may be the key to implementing a multi-client concurrent connection.

Request Class

Request is a subclass of Qthread, which creates a new thread for each descriptor to process it, essentially processing the requests of each client. The core of the request class is Request::run (), which also implements the base function of the incommingconnection new socket, which is invoked through start ().

void Request::run(){    socket = new QTcpSocket();    //用socket描述符作为新socket的描述符    if (!socket->setSocketDescriptor(socketDescriptor))        return;    connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()),    Qt::DirectConnection);    exec();}

This function needs to use Socketdescriptor as a descriptor for the new Qtcpsocket object.

If you want to handle an incoming connection as a new Qtcpsocket object in another thread you had to pass the SOCKETDESCR Iptor to the other thread and create the Qtcpsocket object there and use its Setsocketdescriptor () method.

Note that the last line of the function is exec (), which goes into the event loop, and also has the EXEC () function in Serverthread::run ().

When the data is ready to be read, the kernel select emits a readyread () signal to trigger the Onreadyread () function. In this way, Onreadyread () is the most important function same strain down.

Onreadyread function

This function begins to parse the request data sent by the client and constructs the encapsulated response data.

Here is the standard request Headers and response Headers that are crawled with the browser.

The order of execution in the Onreadyread function is as follows:

    1. Getrequestheader
      Responsible for reading the request headers, confirming that the client requires a long \ Short connection.

    2. Tryresponsefile
      Returns the directory of the request path in 4 scenarios. Responsedirectory () Return to the table of contents, return directly to the page; 404;403

    3. Resonsefile
      Call Response->response to return to the Web page

    4. Clearstatus
      If it is a long connection, clearstatus () continues after the socket is monitored. At the same time, delete the socket connection if it exceeds timeout. If it is a short connection, remove the socket connection directly.

Summarize

Singleton pattern is used in the log system and configuration system, which is not thread-safe in this example.

Reference

[1].http://blog.chinaunix.net/uid-27685749-id-3847998.html

[2].http://www.linuxidc.com/linux/2011-03/33810p2.htm

[3].http://blog.csdn.net/envenler/article/details/8020064

[4].http://blog.csdn.net/jandunlab/article/details/14108595

[5].http://blog.sina.com.cn/s/blog_a6fb6cc90101hohu.html

[6].http://qimo601.iteye.com/blog/1407911

HTTP Server implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.