I brewed a simple Python-based http server using sockets today and I wanted to share the code, along with some comments. Sure, there is the http.server class, but why not have some fun? Building a fully-fledged HTTP server is a big undertaking. I focused on building a small server, supporting only the basic functionality of the Hyper Text Transfer Protocol (namely the GET and HEAD request methods).
Some basic info
In short, HTTP is a request-response protocol. The web browser attempts to connects to the http server, HTTP server (usually) accepts the connection requests and goes into receiving mode. The client (e.g. web browser) sends one of the nine request methods to the server, along with the methods arguments. Server then processes the request and issues appropriate response. An example request looks like this:
As I have already mentioned, my server support only a GET and HEAD request method. the GET request method request specific a resource from the server. The server responds with headers and the resource body. The HEAD method is similar to GET, it differs in that the server responds only with the headers. This can be useful when a client wants to determine whether e.g. a time stamp on a resource has changed, and whether it has to be re-requested.
I designed by server class to expect a port number on which it is to listen for connection, with a default value of 80. However you might need to run the server script in a privileged mode in order to successfully acquire this (or any other low) port from your system. Thus, in case the script fails to acquire the default or user provided port, it will attempt to acquire port 8080 as a last resort.
When the client requests a resource, the server attempts to open it from the local www/ folder. If the resource is present, server serves it, accompanied with appropriate headers (status 200 OK). If the resource is not present, the server then serves a error 404 web page, along with a slightly different header set describing the encountered problem.
Notice, that web server does parse in any way the GET arguments if they are provided in the URL (URL encoded arguments, in the form of index.html?arg1=val1&arg2=val2). It does, however, strip them from the URL, if they are present and servers the resource. Also note that this server runs only a single thread, thus serving one user at a time. The server is not meant to be fast nor secure. I must say that coding this server made for fun-filled afternoon. If I will have some free time in the future maybe I will extend it’s functionality a bit.
Example request-reply
Sample HEAD request to my server issued by Firefox
HEAD /index.html HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive
The most important is the first line. It specifies the request method (HEAD) and it’s arguments, most notably the file which is being requested. The second lines specifies the internet host and port of the resource requested. Lack of port following the local host implies port 80. More on the following lines can be found here. Response
Sample response headers sent from the server to the client:
HTTP/1.1 200 OK Date: Sat, 19 Mar 2011 16:42:17 Server: Simple-Python-HTTP-Server Connection: close
Notice, that it’s only basic response, containing only some basic information — most notably the first line, confirming that the requested resource exists. For the contrast, here is a sample response header from the server after the client had requested a non-existing resource:
HTTP/1.1 404 Not Found Date: Sat, 19 Mar 2011 16:44:53 Server: Simple-Python-HTTP-Server Connection: close
Final HTTP server code
And now for the code. Oh, and here’s the code along with some simple html/css/jpg files for testing: python-http-server.tar.gz. Also, you might want to check out some kind of a browser plugin which allows to issue custom HTTP request methods and view the response, such as this one.
#!/usr/bin/python import socket # Networking support import signal # Signal support (server shutdown on signal receive) import time # Current time class Server: """ Class describing a simple HTTP server objects.""" def __init__(self, port = 80): """ Constructor """ self.host = '' # <-- works on all avaivable network interfaces self.port = port self.www_dir = 'www' # Directory where webpage files are stored def activate_server(self): """ Attempts to aquire the socket and launch the server """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # user provided in the __init__() port may be unavaivable print("Launching HTTP server on ", self.host, ":",self.port) self.socket.bind((self.host, self.port)) except Exception as e: print ("Warning: Could not aquite port:",self.port,"\n") print ("I will try a higher port") # store to user provideed port locally for later (in case 8080 fails) user_port = self.port self.port = 8080 try: print("Launching HTTP server on ", self.host, ":",self.port) self.socket.bind((self.host, self.port)) except Exception as e: print("ERROR: Failed to acquire sockets for ports ", user_port, " and 8080. ") print("Try running the Server in a privileged user mode.") self.shutdown() import sys sys.exit(1) print ("Server successfully acquired the socket with port:", self.port) print ("Press Ctrl+C to shut down the server and exit.") self._wait_for_connections() def shutdown(self): """ Shut down the server """ try: print("Shutting down the server") s.socket.shutdown(socket.SHUT_RDWR) except Exception as e: print("Warning: could not shut down the socket. Maybe it was already closed?",e) def _gen_headers(self, code): """ Generates HTTP response Headers. Ommits the first line! """ # determine response code h = '' if (code == 200): h = 'HTTP/1.1 200 OK\n' elif(code == 404): h = 'HTTP/1.1 404 Not Found\n' # write further headers current_date = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) h += 'Date: ' + current_date +'\n' h += 'Server: Simple-Python-HTTP-Server\n' h += 'Connection: close\n\n' # signal that the conection wil be closed after complting the request return h def _wait_for_connections(self): """ Main loop awaiting connections """ while True: print ("Awaiting New connection") self.socket.listen(3) # maximum number of queued connections conn, addr = self.socket.accept() # conn - socket to client # addr - clients address print("Got connection from:", addr) data = conn.recv(1024) #receive data from client string = bytes.decode(data) #decode it to string #determine request method (HEAD and GET are supported) request_method = string.split(' ')[0] print ("Method: ", request_method) print ("Request body: ", string) #if string[0:3] == 'GET': if (request_method == 'GET') | (request_method == 'HEAD'): #file_requested = string[4:] # split on space "GET /file.html" -into-> ('GET','file.html',...) file_requested = string.split(' ') file_requested = file_requested[1] # get 2nd element #Check for URL arguments. Disregard them file_requested = file_requested.split('?')[0] # disregard anything after '?' if (file_requested == '/'): # in case no file is specified by the browser file_requested = '/index.html' # load index.html by default file_requested = self.www_dir + file_requested print ("Serving web page [",file_requested,"]") ## Load file content try: file_handler = open(file_requested,'rb') if (request_method == 'GET'): #only read the file when GET response_content = file_handler.read() # read file content file_handler.close() response_headers = self._gen_headers( 200) except Exception as e: #in case file was not found, generate 404 page print ("Warning, file not found. Serving response code 404\n", e) response_headers = self._gen_headers( 404) if (request_method == 'GET'): response_content = b"<html><body><p>Error 404: File not found</p><p>Python HTTP server</p></body></html>" server_response = response_headers.encode() # return headers for GET and HEAD if (request_method == 'GET'): server_response += response_content # return additional conten for GET only conn.send(server_response) print ("Closing connection with client") conn.close() else: print("Unknown HTTP request method:", request_method) def graceful_shutdown(sig, dummy): """ This function shuts down the server. It's triggered by SIGINT signal """ s.shutdown() #shut down the server import sys sys.exit(1) ########################################################### # shut down on ctrl+c signal.signal(signal.SIGINT, graceful_shutdown) print ("Starting web server") s = Server(80) # construct server object s.activate_server() # aquire the socket
Josephpex
/ 2021/01/25[url=https://rusmp3.xyz]русская песнь[/url]
ErnestSaulp
/ 2021/01/25[url=https://rusmusic.xyz]песнь песней онлайн[/url]
JamesWen
/ 2021/01/25[url=https://manymp3.xyz/]бесплатно mp3 все песни в хорошем качестве[/url]
Marcigon
/ 2021/01/24[url=https://uptodateksa2.trwatch.info/mn-wm-tmkn/qIh4z8DdhK3ZgZ4][img]https://i.ytimg.com/vi/uPAjZwSJvL8/hqdefault.jpg[/img][/url]
Щ…Щ†ШёЩ€Щ…Ш© [url=https://uptodateksa2.trwatch.info/mn-wm-tmkn/qIh4z8DdhK3ZgZ4]ШЄЩ…ЩѓЩ†[/url] Щ…Щ† Ш§Щ„ШЄШЩѓЩ… ШЁШ§Щ„ЩѓШ§Щ…Щ„ Щ„ШЈШ¬Щ‡ШІШ© Ш§Щ„Щ…Щ†ШІЩ„ Ш§Щ„Ш°ЩѓЩЉШ©LG ThinQ
Loan
/ 2021/01/23[url=https://wpaloans.com/]unsecured loan[/url] [url=https://otaloans.com/]consolidated debt relief[/url]
SusanSkymn
/ 2021/01/23[url=https://oddlifecrafting.eswindow.info/kLGHcJ6a3HmRtKM/plywood-shower.html][img]https://i.ytimg.com/vi/_xS9ifyH_Nk/hqdefault.jpg[/img][/url]
Plywood Shower Cabin Part 2 (TURNING IT WATERTIGHT) рџ›Ѓ Living [url=https://oddlifecrafting.eswindow.info/kLGHcJ6a3HmRtKM/plywood-shower.html]Tiny[/url] Project #079
Evanef
/ 2021/01/22[url=http://atenololtenormin.com/]atenolol cream[/url]
Jacknef
/ 2021/01/22[url=https://amoxicillindrug.com/]cheapest prices for generic amoxicillin[/url] [url=https://phenerganpromethazine.com/]can you buy phenergan over the counter[/url] [url=https://synthroidlevo.com/]synthroid 50 mcg tablet[/url]
DianneExhaf
/ 2021/01/21[url=https://meilleurarab.frpost.info/on-fait-du-surf-lad-ter-30-ft-zeguerre-nono/w2-4paGyidivrn8.html][img]https://i.ytimg.com/vi/_7WAnMVszuI/hqdefault.jpg[/img][/url]
ON FAIT DU SURFрџЊґ – #LaDГ©ter 30 [url=https://meilleurarab.frpost.info/on-fait-du-surf-lad-ter-30-ft-zeguerre-nono/w2-4paGyidivrn8.html](ft.[/url] ZeGuerre, Nono)
Vladimirqxs
/ 2021/01/20удалите,пожалуйста! [url=https://spam-rassylka.ru/].[/url]
RandalCof
/ 2021/01/20[url=https://checkmusic.xyz]скачать музыку бесплатно[/url]
Michaelsop
/ 2021/01/20[url=https://soundplayer.xyz]слушающий музыку[/url]
Brianagige
/ 2021/01/20[url=https://musplayer.xyz]скачать мп3[/url]
RobertPal
/ 2021/01/19[url=https://mp3super.xyz]слова песни[/url]
DavidWek
/ 2021/01/19[url=https://justmp3.xyz]песнь популярные[/url]
Jeffreycit
/ 2021/01/18[url=https://playmp3.xyz]песня девочка[/url]
Louisewag
/ 2021/01/18[url=https://theodd1soutcomic.eelong.info/my-poetry-teacher/rXnd3I14eYZ_qoI][img]https://i.ytimg.com/vi/wDyxXGCVIuI/hqdefault.jpg[/img][/url]
[url=https://theodd1soutcomic.eelong.info/my-poetry-teacher/rXnd3I14eYZ_qoI]My Poetry Teacher[/url]
Clintonovalf
/ 2021/01/18[url=https://mp3planet.xyz]лучший песнь[/url]
Dennisgon
/ 2021/01/18[url=https://formusic.xyz]песнь лета[/url]
Richardtot
/ 2021/01/18[url=https://kachaimp3.xyz]песни 2021[/url]
Cash Loan
/ 2021/01/18[url=http://mustlending.com/]5000 loan with bad credit[/url] [url=http://remiloans.com/]loan repayment options[/url] [url=http://elmaloans.com/]personal bad credit loans[/url] [url=http://midiloans.com/]specialized loan services[/url] [url=http://lemloans.com/]bank loan[/url] [url=http://loansbn.com/]loan fast[/url] [url=http://loansmf.com/]loan til payday[/url] [url=http://koaloans.com/]short loans online[/url]
JanetRom
/ 2021/01/17[url=https://gesieltaveira.brdesk.info/redmi-9c/o4rPe8rPi8ZmsWc][img]https://i.ytimg.com/vi/oRjIinUa3K4/hqdefault.jpg[/img][/url]
Redmi 9C, tome CUIDADO com esse XIAOMI Veja o MOTIVO Unboxing e [url=https://gesieltaveira.brdesk.info/redmi-9c/o4rPe8rPi8ZmsWc]ImpressГµes[/url]
Kimnef
/ 2021/01/14[url=https://hydroxychloroquinehcqn.com/]plaquenil 200mg price in india[/url]
CaroleKet
/ 2021/01/14[url=https://shrutiarjunanand.mrslow.info/affordable-vs-high-end-complete-indian-bridal-makeup-kit-for-beginners-anaysa-shrutiarjunanand/y7hhlaeCcqWD2qU.html][img]https://i.ytimg.com/vi/hR10BMBrLws/hqdefault.jpg[/img][/url]
Affordable vs High End – Complete Indian Bridal Makeup Kit [url=https://shrutiarjunanand.mrslow.info/affordable-vs-high-end-complete-indian-bridal-makeup-kit-for-beginners-anaysa-shrutiarjunanand/y7hhlaeCcqWD2qU.html]For[/url] Beginners#Anaysa #ShrutiArjunAnand
Janenef
/ 2021/01/14[url=https://creamtretinoin.com/]tretinoin 5 gel[/url]
Kimnef
/ 2021/01/10[url=https://nolvadexgen.com/]tamoxifen 2017[/url]
Online Loan
/ 2021/01/10[url=https://threeloans.com/]500 cash loan[/url]
Vladimiryzw
/ 2021/01/08удалите,пожалуйста! [url=https://spam-rassylka.ru/].[/url]
Janenef
/ 2021/01/06[url=https://weppills.com/]zestoretic 10[/url]
Vladimirpbf
/ 2021/01/05удалите,пожалуйста! [url=https://spam-rassylka.ru/].[/url]
EileenTieme
/ 2021/01/03[url=https://sharmaji.inhistory.info/f3eG0W-BgKXPm5E/amitbhai-vs.html][img]https://i.ytimg.com/vi/NDTl9HOnjeY/hqdefault.jpg[/img][/url]
AmitBhai Vs World ChatNo Gun ChallengeFree Fire 1 Vs 1Desi [url=https://sharmaji.inhistory.info/f3eG0W-BgKXPm5E/amitbhai-vs.html]Gamers[/url]
Lisanef
/ 2021/01/03[url=https://ivermectinchem.com/]ivermectin eye drops[/url]
Kianef
/ 2020/12/30[url=http://pharmotk.com/]cozaar generic[/url]
Samuelsep
/ 2020/12/30Посмотрите мой сайт
—-
[url=https://gosuslugi.name/]gosuslugi.ru личный кабинет zakaznoe.pochta.ru[/url]
NorineAlits
/ 2020/12/28[url=https://dakreekcraft.ltheat.info/how-to-unlock-russo-s-sword-of-truth-rb-battles-sword-roblox-build-a-boat/f4yJenmwfnisnak][img]https://i.ytimg.com/vi/KSQCHxJGwew/hqdefault.jpg[/img][/url]
How To Unlock RUSSO’S SWORD OF TRUTH [url=https://dakreekcraft.ltheat.info/how-to-unlock-russo-s-sword-of-truth-rb-battles-sword-roblox-build-a-boat/f4yJenmwfnisnak](RB[/url] Battles Sword)Roblox Build A Boat
StacyLiaft
/ 2020/12/27[url=https://travelthirstyblog.mrblock.info/rXrRg5_Hz8yEs38/thai-food-garlic-pepper-steak-aoywaan-bangkok-thailand][img]https://i.ytimg.com/vi/LHkNjaigOPI/hqdefault.jpg[/img][/url]
Thai Food – GARLIC PEPPER STEAK Aoywaan [url=https://travelthirstyblog.mrblock.info/rXrRg5_Hz8yEs38/thai-food-garlic-pepper-steak-aoywaan-bangkok-thailand]Bangkok[/url] Thailand
Williamerods
/ 2020/12/26мой сайт про активацию windows 7
—
[url=https://aktivator-windows-7.net/]активатор windows 7 домашняя[/url]
Williamhes
/ 2020/12/26[url=https://newmp3.top]скачать музыку бесплатно 2021[/url]
Henryhic
/ 2020/12/26[url=https://funmusic.mobi]слушать песни в хорошем качестве[/url]
Evanef
/ 2020/12/25[url=http://ivermectinxr.com/]ivermectin buy nz[/url]
DavidTop
/ 2020/12/24[url=https://ritm.mobi/]хорошую музыку бесплатно[/url]
HowardNiz
/ 2020/12/24[url=https://ourmusic.site/]русская песнь[/url]
JamesTox
/ 2020/12/24[url=https://mp3store.site/]песня самая самая[/url]
Matthewven
/ 2020/12/24[url=https://mp3click.site/]песни онлайн в хорошем качестве[/url]
Scottbop
/ 2020/12/24[url=https://popsong.site/]включи песню[/url]
Eliastet
/ 2020/12/24[url=https://newsong.site/]скачать музыку бесплатно на телефон[/url]
Changelalf
/ 2020/12/24[url=https://muzicon.site/]музыка вк[/url]
Jamesmiz
/ 2020/12/23[url=https://topmuzyka.mobi/]песня слезы[/url]
Jerryquash
/ 2020/12/23[url=https://coolmp3.site/]сборник музыки[/url]
Jesussnips
/ 2020/12/23[url=https://mp3dream.site/]скачать песню ремикс[/url]