I thought I had this all figured out, but now that I'm writing a webserver, something is not quite working right.
The app listens on a port for incoming requests, and when it receives one, it reads everything up to the sequence "\r\n\r\n". (Because that signifies the end of the headers - yes, I am ignoring possible POST data.)
Now, after it reads that far, it writes to the socket the response:
HTTP/1.1 200 OK\r\n
Host: 127.0.0.1\r\n
Content-type: text/html\r\n
Content-length: 6\r\n
\r\n
Hello!
However, when Firefox or Chrome tries to view the page, it won't display. Chrome informs me:
Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error.
What am I doing wrong?
Here is some of the code:
QTcpSocket * pSocket = m_server->nextPendingConnection();
// Loop thru the request until \r\n\r\n is found
while(pSocket->waitForReadyRead())
{
QByteArray data = pSocket->readAll();
if(data.contains("\r\n\r\n"))
break;
}
pSocket->write("HTTP/1.0 200 OK\r\n");
QString error_str = "Hello world!";
pSocket->write("Host: localhost:8081\r\n");
pSocket->write("Content-Type: text/html\r\n");
pSocket->write(tr("Content-Length: %1\r\n").arg(error_str.length()).toUtf8());
pSocket->write("\r\n");
pSocket->write(error_str.toUtf8());
delete pSocket;
I figured it out!
After writing the data to the socket, I have to call:
pSocket->waitForBytesWritten();
...or the buffer does not get outputted.
Could the problem be that you're not flushing and closing the socket before deleting it?
EDIT: George Edison answered his own question, but was kind enough to accept my answer. Here is the code that worked for him:
pSocket->waitForBytesWritten();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With