How to Write a Web Server in Under 50 Lines

initialize a socket, bind it to a port, and listen for a request., When a request is received, parse the request. , if the request is a "GET" request, it will be of the form:"GET " ,If the file requested isn't present, send a '404' message through...

16 Steps 1 min read Advanced

Step-by-Step Guide

  1. Step 1: initialize a socket

    Again, this script does not implement the whole HTTP protocol and is not suitable for production use.

    It is, however, very useful as a means of illustrating the basic functionality of a web server. ,, To run it, invoke the following on the command line:"python sever.py ".

    If you are running a Posix/Unix OS (ex.

    Linux or Mac OS X), you will need to run this with root privileges (append 'sudo' to beginning of the command or run in a superuser session).

    To make a request of the server, you can open up a browser window and type the following into the address bar: "http://localhost:/" The browser should receive and render the requested file, or a 404 message.
  2. Step 2: bind it to a port

  3. Step 3: and listen for a request.

  4. Step 4: When a request is received

  5. Step 5: parse the request.

  6. Step 6: if the request is a "GET" request

  7. Step 7: it will be of the form:"GET "

  8. Step 8: If the file requested isn't present

  9. Step 9: send a '404' message through the socket

  10. Step 10: if the file requested is present

  11. Step 11: send its contents through the socket

  12. Step 12: preceded by a '200 OK' status message.

  13. Step 13: Steps 2-5 occur in an infinite loop

  14. Step 14: and the script can be exited with 'ctrl+c'.

  15. Step 15: The script in its entirety:

  16. Step 16: You will want to copy it to an empty file and save it as "server.py".

Detailed Guide

Again, this script does not implement the whole HTTP protocol and is not suitable for production use.

It is, however, very useful as a means of illustrating the basic functionality of a web server. ,, To run it, invoke the following on the command line:"python sever.py ".

If you are running a Posix/Unix OS (ex.

Linux or Mac OS X), you will need to run this with root privileges (append 'sudo' to beginning of the command or run in a superuser session).

To make a request of the server, you can open up a browser window and type the following into the address bar: "http://localhost:/" The browser should receive and render the requested file, or a 404 message.

About the Author

M

Martha Murphy

Creates helpful guides on cooking to inspire and educate readers.

37 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: