How does the HTTP protocol work exactly?
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?
Her开发者_如何学JAVAe 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();
What you’ve shown looks okay, so it must be that you’re actually sending something different. (I presume that you're entering "http://127.0.0.1" in your browser.)
Download the crippleware version of this product and see what it reports:
http://www.charlesproxy.com/
Try it with telnet or nc (netcat) to debug it. Also, is it possible you're sending double newlines? I'm not sure your language, so if your print
appends a newline, switch to:
HTTP/1.1 200 OK\r
It's also handy to have a small logging/forwarding program for debugging socket protocols. I don't know any offhand, but I've had one I've used for many years and it's a lifesaver when I need it.
[Edit] Try using wget to fetch the file; use the -S -O file to save the output to a file and see what's wrong that way.
[#2]
pSocket->write(error_str.toUtf8());
delete pSocket;
I haven't used Qt for a long time, but do you need to flush or at least close the socket before deleting?
精彩评论