I have a very simple web sever written in Python. It listens on port 13000, how can I make it deliver a simple "Hello World" webpage if http://localhost:13000
is opened in browser?
Right there is my code:
# set up socket and connection
while True:
sock, addr = servSock.accept()
# WHAT GOES HERE?
sock.close()
As you can see, I am not exactly sure how to actually send back the webpage?
I only have to use the socket
library.
EDIT: The problem is not that I don't know how to formulate the HTTP response, I don't know how to actually make it display in my browser! It just keeps spinning/loading.
Updated according to question change
Possibly, it keeps spinning because in combination of absense of
Content-Length
andConnection
headers, browser may assume it'sConnection: keep-alive
, so it continues to receive data from your server forever. Try to sendConnection: close
, and pass actualContent-Length
to see if that helps.Won't this do what you expect it to? :)
For more detailed description, please see description of HTTP protocol.
or, if you just don't want to remember the full protocol, you can find it again using :
well, you shall usually prefer a site that is less verbose (usually serving only a static file) than stackoverflow ;)
The minimal requirements (you'll find on the answer) is :
two returns are mandatory for the server to get the answer, otherwise the browser waits indefinitely for headers
But to mimic the behaviour of a webserver, don't forget to send your answer only after the browser sends you some data followed by two carriage returns, usually you can get what it sends using :
so you can improve your test routines
I took a previous answer and edited the code for Python3 utf-8 and bytes encoding. Thanks for the original answer it helped out a lot.
You might want to Checkout web objects http://www.webob.org/
It's a simple lightweight project for creating http compatible requests and responses. You can do just about anything with you requests/response objects ... Or just delegate the heavy lifting to WebObjects
Sample
Send back something like:
Then the actual html code. Make sure there is a newline after the Content-Type line and before the html.