PDA

View Full Version : Simple Threaded Http Server



obi
19th October 2009, 20:33
Hello,

I need a simple Http Server. I found the following example:
http://doc.trolltech.com/solutions/4/qtservice/qtservice-example-server.html

Until now, the Code is pretty much the same, but I created a for every incoming connection a QThread which has a QTcpSocket Object.

My problem is: When I start my Server and open the ip and port with my browser, the browser should send a GET request which I want to read with the readClient() function. My problem is: I can write to my socket and send something back to the browser that is no problem, but there is never a readyRead() signal emitted and there is no data to read. There should be at least the GET request in the QTcpSocket or am I wrong? Is there anything I have to care about when I use Threads with QTcpSocket?

I hope I could describe my problem. If not, I'll see that I could get some Code the next days... It's at work.

Thanks in advance

wysota
20th October 2009, 00:03
Do you remember about running an event loop in each of the threads?

By the way, a thread-per-connection design is very inefficient. It's better to have a limited number of threads each handling a defined number of connections simultaneously.

obi
20th October 2009, 09:35
Okay here is some Code:



void CHttpThread::run()
{
QTcpSocket socket;
socket.setSocketDescriptor( m_socketDescriptor );

socket.waitForReadyRead( 3000 );

socket.close();
connect( &socket, SIGNAL( disconnected() ), this, SLOT( quit() ) );
connect( &socket, SIGNAL(readyRead()), this, SLOT(readClient()) );
exec();
}


Hope you could help me!

obi
20th October 2009, 10:09
Finally it works, but:

If i want to make it more efficient, the way would be to create a limited number of Threads, and in this Threads create a limited number of QTcpSocket Object for every connection?

wysota
20th October 2009, 10:42
Have a pool of threads and a queue of connections. When a new connection comes in, assign it to one of idle threads if there are any or queue the connection so that when a thread becomes idle, it will pick it up and handle it. When a thread handles a predefined number of requests (say.... 200?) it dies and a new thread is spawned in its place. You can use the same model with processes instead of threads.