Programming Memoirs

Simple Python HTTP server using sockets

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

48 ResponsesLeave one →

  1. Paying for leads is not a bad thing at all. Its heater main can be uncovered within the cabin of your car or truck, merely in the firewall. Nonetheless, it is a result in for worry to parents while a lot of these kind of games incorporate materials that aren’t fit for children. It also improves vigor, vitality and endurance to last longer in bed and mesmerize her in bed. In addition, you should also choose wedding invitation envelopes in creative and unique design in order to complete the beauty of the invitation card. [url=http://www.cheapwholesalenflfootballjerseys.com/]Wholesale Jerseys USA[/url]. For children which enjoy animals, a number of of these kinds of stuff function animals. Those cheap locks one can buy from big box stores can be opened even without the help of a reputable locksmith Philadelphia. Study the causes employed by the ESRB for classification, to see if they are appropriate to you. Make a note of the number. However,[url=http://www.cheapwholesalenflfootballjerseys.com/]Wholesale Jerseys[/url], in the case of overfill prevention, the cylinder valve caps have a one piece cap with a retaining strap attached to the valve. He is the state dog of Wisconsin. Eye color should correspond with coat color.[url=http://www.cheapwholesalenflfootballjerseys.com/]Cheap Jerseys Wholesale China[/url].//////////

    Reply
  2. заказать продвижение сайта москва логин в скайпе SEO PRO1

    Reply
  3. With a little education, you can be working in this exciting business helping drivers to maintain safe and working vehicles.To enroll in the best school, firstly you will need to ask the syllabus given at that school. Money saving deals of men and women try looking in advance to buying the brand new dwelling for home so they really make an effort to gain a number of funds should you book than their unique current residence. [url=http://www.wholesalejerseyscheapnfl.us.com/]Wholesale NFL Jerseys[/url]. Then move their benefit,[url=http://www.wholesalejerseyscheapnfl.us.com/]Wholesale NHL Jerseys Online[/url], your e book, toward a personal seated within just entrance of on your own and check with them in the direction of go it again in direction of the particular person at the back again of the space.It is also necessary for you to have a driver’s license. Apart from that the rate of employment opportunity is also high with increasing number of dispensaries and hospitals in India. Maintenance the QuickBooks set up making use of Insert Eliminate Designs remedy within Deal with Panel. Individuals these days are very much weight conscious but this realization dawns on them only if they end up bitten through overweight issues and this is when they appear for solutions such as sauna for weight loss. Check the overall quality of facilities. Shockingly, Reputation harm might rise up out of obviously minor issues which can break down quite rapidly with notice or plan of action. All right, allow’s hope your self comprise proven Rapport with your client or chance and oneself consist of known a scenario they contain in which a content by yourself supply may be instructive towards them.[url=http://www.wholesalejerseyscheapnfl.us.com/]Cheap NHL Jerseys[/url]. If you write about useful, value added information that appeals to their readers, they probably won’t mind if you add links to your other articles.Visit my sitehttp://www.wholesalejerseyscheapnfl.us.com/

    Reply
  4. This helps us also if a problem arises we can go check it out and keep all the information always constantly updated.A symbol of status for many and an icon of achievement in the country, owning a car by Mercedes Benz displays great taste, smart decisions and announces that you have arrived in the world. With the different equipments available, you learn about operation modes so that when you get employment, you can operate them well. Prior to numerous quite a while the specific situation turns up to have already been unique making use of constricted Kolkata Model brand new that may be as well costly.jpg" alt="ASTER SHREE GARDEN SRIRAMPUR HOOGHLY"width="450"eight="450" >< a>Srirampur would be the several remarkable spots if it arrive at Brand new Dwelling inside Kolkata plus they’re proven at most created a component of Srirampur.Regardless of the point that vast majority of the games educate website stay on burn in addition tend in direction of keep modest than their desktop in addition software counterparts, the model beneath game play amongst the full region barely everlasting visual near the inexperienced gamer. [url=http://www.jerseyssportsshop.com/]Cheap NFL Jerseys China Online[/url]. By yourself include in direction of position inside some effort and hard work for turning into a suitable anti virus since it is over the basic safety of your beneficial digital resources.[url=http://www.jerseyssportsshop.com/]Cheap Jerseys China Online[/url]. This first and foremost unique beneficiary of being economical surely lures us into buying a car seat stroller sans any doubts and worries on your pockets.45 lakhs. If you want to hear more, come see my about.[url=http://www.jerseyssportsshop.com/]Wholesale Jerseys Supply[/url]. This means those who choose to be trained in this field have various openings and getting a job is quite easy. It should include all the vital courses as safety courses, equipment handling training and apprenticeship.Visit my site:http://www.jerseyssportsshop.com/

    Reply
  5. In the end, reading programs are excellent for kids of all ages. Many clubs invite people of all ages, and this is a great way to improve one’s outlook on the world. To reinforce these pointed out OsgoodSchlatter therapy, discomfort relieving treatment and ice compress will help reduce the inflamed portion from the knee muscular tissues. [url=http://www.wholesalenfljerseysonline.us.com/]Cheap Jerseys China[/url]. Grants range from field to subject, but it is doable to seek out monetary help for nearly every kind of sports actions a student has taken half in. All you need to do would be to access all of them, share your opinions and budget with them and see them materializing the ideal! Author Resource:All You Need To Know About the Best Project Developers.com newresidentialprojectsinkolkatanewconstructioninkolkata " target="_blank">http:firstkolkataproperties. Seniors can also be chosen to Dexter USBC High School AllAmerican Workforce and win a $1,000 scholarship. We have helped more than 20,000 students in last 5 years. The major mistakes that the simulator detects are identified below.[url=http://www.wholesalenfljerseysonline.us.com/]Wholesale NFL Jerseys[/url].Sales and seasonal promotions are great for attracting large numbers of new consumers.[url=http://www.wholesalenfljerseysonline.us.com/]Cheap Jerseys China Wholesale[/url].Steel and aluminum garage doors are printed with contemporary grain patterns or at least so that you have a evenly finish. Metal garage doors have a the thought of grain stop and for that reason that they supply you with the going to be the impression of since they will be ach i like your Wooden garage doors aren’t installed as regularly as a long time ago however many are you aware that garage door by the way are nonetheless available.Visit my sitehttp://www.wholesalenfljerseysonline.us.com/

    Reply
  6. That’s what the pros do. This is a single of the unneeded aspect repercussions of the online globe. Some outstanding schemes embrace The Annual Zeb Scholarship, Chuck Hall Star of Tomorrow and Earl Anthony Memorial Scholarships. [url=http://www.wholesale-cheapnfljerseys.us.com/]Cheap NFL Jerseys China[/url]. Many children love being outside, so make it an educational experience. They have been helping in the market for many years and have earned a respectable as well as reputed place amongst the great deal.Think about it, if you make every shot with a faultless lie, with absolutely no wind, and with zero barierss to play around, then what would be the challenge? Of course the game would be much easier and you would probably score very well on each game you play,[url=http://www.wholesale-cheapnfljerseys.us.com/]Wholesale Jerseys China[/url], but there’s no zest when constantly playing in perfect conditions, no adaptation required, nothing to test our abilities at golf, nothing to learn.Most it is certainly plausible are acquiring chrome steel or at least aluminum garage doors. Also, it is wise to wear gloves or perhaps some type of safety yourself because any deposits from possibly medications or even treatments can impact you too. This problem can quite possibly affect the sudden development amid adolescents commonly often called growth spurt. Like ourselves, their medicines should be given accordingtostrict measurement and regulation. Aside of program in opposition to knowing it in the course of the Quite expression alone, a virus is basically a software program designed totally in direction of wreak havoc upon your laptop or computer. Your projects are handled by an efficient panel of professionals.[url=http://www.wholesale-cheapnfljerseys.us.com/]Cheap Soccer Jerseys Wholesale[/url].Visit my site:http://www.wholesale-cheapnfljerseys.us.com/

    Reply
  7. Apps have helped such businesses to successfully promote their business on a digital platform and that is apps.Land surveyor Virginia experts are definitely doing a great job. CPM selling prices within alternative Varrie Nations.Amount of ExerciseThe Customized Fat Loss program software can help you determine your system type so that you do not have to know what it is.To develop a working marketing plan for yourself, take the advice that other people have discovered. [url=http://www.cheapfootballjerseysnfl.us.com/]Wholesale Jerseys Cheap[/url]. Just about all commercial establishments require a foot hold throughout Mumbai. Mainly because it provides the player this to kill mob easily but this could also hit you up for in addition. This advice will give you what you need to make the right decisions and how to go about it.[url=http://www.cheapfootballjerseysnfl.us.com/]Cheap NFL Jerseys From China[/url]. Therefore, you will need to look at the number of years that they have been in business. When it’s a simple fix,[url=http://www.cheapfootballjerseysnfl.us.com/]Wholesale NFL Jerseys China[/url], do it yourself!If you have doubts about the work of a mechanic or their diagnosis, ask if you can see the old damaged parts. One of these wheels’ best capabilities offer there is a wonderful advantage that a tire for security and greater traction.An Asian escort Sydney knows nicely how to turn a man upon and how to make him feel incredible, while carrying out sex along with him.Visit my sitehttp://www.cheapfootballjerseysnfl.us.com/

    Reply
  8. Szukasz interesującego źródła porad na temat kredytów pozabankowych? W ostatnim czasie kredyt bez bik jest w Polsce bardzo powszechny, jednak niestety nie wszystkie oferty pożyczek są atrakcyjne – głównie po to założyliśmy tę witrynę internetową, aby wreszcie Polacy mogli przekonać się, który kredyt bez zaświadczeń jest godny uwagi pod wszystkimi względami. Całkiem często umieszczamy własne rozważania na temat świeżych ofert parabankowych, zatem wystarczy zaglądać akurat do nas, aby orientować się jaki kredyt gotówkowy jest nisko oprocentowany, pozbawiony ukrytych opłat, etc. [url=https://bezbiku.ebrokerpartner.pl]kredyt bez bik[/url] [url=https://bezbiku.ebrokerpartner.pl]pozyczka bez zaswiadczen[/url] [url=https://bezbiku.ebrokerpartner.pl]pozyczka gotowkowa[/url] Brak pracy, zadłużenie albo beznadziejna płaca nie są kłopotem dla chcących uzyskać kredyt gotówkowy – a przynajmniej mówimy w tej chwili o odwiedzających naszą stronę. Rzeczywistość jest taka, że przedstawiliśmy w serwisie wartościowe porady, które powodują, iż natrafienie na kredyt bez zaświadczeń, oczywiście całkiem korzystnie oprocentowany, nie jest kłopotem. Jednak serwis nie posiada tylko informacyjnego charakteru – również można po prostu załatwić właśnie na nim kredyt bez bik.

    Pewnie chciałbyś wreszcie uzyskać ten kredyt gotówkowy, który sprawi, że zakupisz sobie chociażby telefon komórkowy czy opłacisz dentystę, lecz potem nie będziesz mieć nawet najmniejszych nieprzyjemności. No cóż, niby od czego jest zatem otworzony przez nas serwis internetowy? No co jak co, lecz nikt kto sensownie podejście do lektury treści w serwisie nie będzie mieć żadnych wątpliwości odnośnie tego, który kredyt bez bik, a głównie o kredytach bez konieczności załatwiania zaświadczeń mowa, jest strzałem w dziesiątkę. Naturalnie wszystkie z porad zostały napisane w taki sposób, że definitywnie każdy zrozumie o co chodzi. W końcu kredyt bez zaświadczeń jak najbardziej może być przyjazny. Pod wszystkimi względami.

    Przydatne kompendium informacji dla tego osobnika, który nie za bardzo wie, który kredyt bez bik przynajmniej w tym momencie jest w ścisłej czołówce. Ciężko ogólnie wybrać parabank, ale po lekturze założonego przez nas serwisu wreszcie definitywnie wszystko będzie jasne. Żywimy nadzieję, że kredyt gotówkowy w istocie jest tym czymś na czym świetnie się znamy – reakcje czytelników to potwierdzają. Chętnie odpowiemy na wszelakie pytania jeżeli wchodzi w rachubę kredyt bez zaświadczeń, często aktualizujemy stronę, zatem raczej wszyscy kredytobiorcy powinni być zadowoleni.

    Reply
  9. <p><p style="text-align: justify;">Apart from this, make sure to join only authentic site as it is all about payment, however, don&rsquo;t make it waste at any cost. These boards come in various Sizes. GP practices, particularly at GP partnership level, is definitely not hunting for somebody is a good trainee, needs attention and is also potentially ‘high maintenance’; are going to after people who may add value creating a real contribution, even without using their normal remit.Saleable real estate doings in the city are cover the areas such as Bund Garden Road, Dhole Patil Road, Station Road and RTO and has given way to multiple emerging micro-markets like Kalyani Nagar, Senapati Bapat Road, [url=http://www.wholesalejerseyscheaper.com/]Wholesale NFL Jerseys Cheap[/url], Mundhwa, Aundh, Baner besides Yerwada.[url=http://www.wholesalejerseyscheaper.com/]Cheap Jerseys[/url]. It is equally devastating because it may include an overambitious and the best kinds threatening image. Handguns are simpler to utilise with respect to scaled-down adventure greatly assist accuracy. See the role that you are trying to getIf you’re looking for a GP salaried post, your role will primarily correspond with the availability of clinical services and you may usually have not an issue grasping the needs.[url=http://www.wholesalejerseyscheaper.com/]Cheap Jerseys China[/url].Just like when you paint a wall, applying an epoxy coating to your garage floor will require some prep. If several flavors of yoga are offered in your area, do your research online or in the library to find which style would be the best fit for you. Proceed to your language and also navigate about “Stow Changes. The inception of the internet has made it easy for individuals to enjoy plenty of services at the comfort of their home. Retail outlets and malls are mushrooming all over the place to meet the rapid retail boom and the increasing purchase power parity of the middle class.Visit my site:http://www.wholesalejerseyscheaper.com/

    Reply
  10. The deeper you can cultivate your hole, the better for your tree. [url=https://www.wholesalejerseysweb.us.com/]Cheap Jerseys Wholesale[/url]. You are able to attempt studying about how on the web advertising will help increase your company. Plant ball, burlap and allthe burlap will soon rot away.While Stihl And also Husqvarna claim a major part of the actual chainsaw spot light around the world, Echo has been steadily producing yard for the top 2. At this juncture,[url=https://www.wholesalejerseysweb.us.com/]Wholesale Cheap Jerseys[/url], it is important to become for cautioned.[url=https://www.wholesalejerseysweb.us.com/]Cheap NFL Jerseys Wholesale[/url]. The one and only moment you have to pay the Search Engine is literally once a person clicks on your advertisement. Huge amounts of money were invested in ‘all singing dancing’ sites. In case you have a little fill, be sure that the environment for little loads is now being utilized. Many payment possibilities and currencies are supported so intercontinental browsing is not any concern. Something that is created simply by Makita is always going to be a quality product but their chainsaws carry it to the next levels. In planting trees, their mature height and spread must be considered before a selection is made. This could be everything from starting a blog to networking at a local community event.Visit my sitehttps://www.wholesalejerseysweb.us.com/

    Reply
  11. [url=http://buycoconutoil.us/]coconut oil in vagina[/url]

    Reply
  12. 301 Moved Permanently
    [url=https://www.youtube.com/c/JeffGarnerMusic]Show more>>>[/url]

    Reply
  13. [url=http://buyqsymia.party]qsymia generic[/url]

    Reply
  14. [url=http://buyqsymia.party]buy qsymia online[/url]

    Reply
  15. Сhемicаl рeelіng is а сosmеtiс рrосеdure аіmеd at rеjuvеnаting аnd еliмinаting skin defеcts, for whісh сhемical substаnсеs are used thаt саusе а соntrollеd cheмiсаl
    [url=http://chemicalpeel.in/what-does-chemical-peel-do-to-handle-with-your-skin-defects]http://chemicalpeel.in/what-does-chemical-peel-do-to-handle-with-your-skin-defects[/url]

    Reply
  16. Знакомства Gillett. Сайт знакомств Gillett бесплатно, без регистрации, для серьезных отношений.

    Reply
  17. заказать прогон хрумером логин скайпа pokras7777

    Reply
  18. Polecam [url=http://bulls.net.pl/]w co inwestować małe kwoty[/url] albo polecam to [url=http://bulls.net.pl/]http://bulls.net.pl/[/url]

    Reply
  19. SirFizX

     /  2017/01/16

    Could you create a tutorial that demonstrates how to send files to the server via javascript XMLHttpRequest?

    Reply
  20. What license is this code provided under?

    Reply
  21. Very nice, thanks for the code example, I am still learning python and have been trying to write my own little http server, this is going to help me a lot.

    Reply

Leave a Reply to atopmedumpere