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

6,883 ResponsesLeave one →

  1. [url=https://mp3rave.site]песни ремиксы[/url]

    Reply
  2. [url=https://malegraonline.com/]malegra cheap[/url]

    Reply
  3. [url=https://mp3groove.site]песни ремиксы[/url]

    Reply
  4. [url=https://mp3vibe.site]скачать музыку 2021[/url]

    Reply
  5. [url=https://mp3rider.site]слова песни[/url]

    Reply
  6. The Best Places To Day Hookup Females

    The number of hookup females for starters person is normally small, and this means if you hire a company who is pretty much like yourself in all regards, the odds are very high that they are also apt to be an effective go with for yourself [url=https://wikihookup.com/are-there-any-real-hookup-websites]https://wikihookup.com/are-there-any-real-hookup-websites[/url] Imagine if you don’t have a lot good luck with internet hookups? Properly, there are many approaches that you can start discovering someone to hookup with. While these techniques is probably not as fast as utilizing online dating, they may be far more convenient and therefore are often less costly, which definitely causes them to be a feasible solution.

    Totally free Hookup Ladies: One thing that can be done is to appear on the net for the free of charge courting website. Usually these websites are strictly for single folks, but there are several web sites that serve lovers or friendships as well. Although they are certainly not designed specifically for hookups, you can still find some very good possibilities at free of charge hookups. This is probably not an excellent way for you to fulfill a hookup, but it may be a very good way to find out if this individual is somebody who you would probably feel comfortable with courting or connecting with with a more long lasting foundation.

    Paid Internet dating Services: There are actually on-line solutions like hookup colder and Zoosk that are free to sign up for. They may have both paid and cost-free models, and both of them have their individual benefits. A number of the advantages of a compensated assistance consist of the fact that you know precisely what you will be getting into even before you sign in for your account, which means you may have additional control over the circumstance, and if you choose not to select it, you are able to stop anytime.

    Live Online Hookups: There are many nations where on-line hookup professional services are common. India is one of these nations. In India, a lot of young people, especially individual ladies, will take advantage of the internet to locate an individual to have a a single nighttime stay with. In numerous elements of Asia, individuals will head to karaoke night clubs and general public dances and then try to fulfill somebody for any day. There is a lot of sexual activity involved in fact it is perfectly appropriate in lots of Asian cultures.

    In the usa, hookup online dating sites are becoming more popular. This is because they supply a simple way for people from all of parts of society to discover a person to day. Since several dating sites cost a small monthly charge, there is absolutely no reason why anyone who has an interest in finding someone should struggle to do this on the Internet free of charge. It really is less hazardous than meeting personally, and it also permits you to stay in the security of your personal property. With one of these providers, you are able to search through user profiles and see if there is any individual that you are currently drawn to.

    Transunion: As pointed out above, hookup courting online has its own downsides. The downfall of it is it is incredibly very easy to lay about your grow older, earnings, or marriage reputation. As a result, you could possibly turn out investing several weeks looking for the best go with. One of the best services for finding matches for queers is TransUnion. The best thing about this is that you could get credit checks, shell out almost no, and perhaps you will definitely get immediate credit history approval.

    I would personally definitely propose these three providers as the best way to hookup with females. Should you choose to use cost-free internet dating sites, make sure you seek information before you sign up. Some websites are fake, deceptive, and might cause damage to your future. Recall to determine the online privacy policy and guidelines in the site, and be sure that the website has been around for a serious while. Each one of these factors will assist you to get the best support to suit your needs.

    Hookups with women is a wonderful way to satisfy a brand new partner and encounter a whole new tradition. If you are looking to date a female online, bear in mind that there are several fraudulent internet dating sites. The best recommendation is to look into the Greater Enterprise Bureau before employing any internet dating professional services. It’s always advisable to be secure than sorry. Whether you want to use on the web hookup professional services or otherwise not, there are plenty of individuals who are trying to find a partnership just like you.

    Reply
  7. [url=https://latenightseth.usplane.info/baio-dead/pGyqrc2NZn-v3NY][img]https://i.ytimg.com/vi/p7EIlT1Fxvs/hqdefault.jpg[/img][/url]

    [url=https://latenightseth.usplane.info/baio-dead/pGyqrc2NZn-v3NY]Baio: Dead Hand Control[/url]

    Reply
  8. [url=https://musicmix.mobi]сборник музыки[/url]

    Reply
  9. [url=https://musicintro.mobi]скачать музыку с вк[/url]

    Reply
  10. [url=https://mp3remix.mobi]качество музыки[/url]

    Reply
  11. [url=https://mp3duet.mobi]песня мама[/url]

    Reply
  12. [url=https://muspause.mobi]песни 2021 бесплатно[/url]

    Reply
  13. [url=https://tonnazvuka.top]бесплатные песнь[/url]

    Reply
  14. [url=https://wowmp3.top]музыка бесплатно[/url]

    Reply
  15. [url=https://dalasreview.alclip.info/AHTp6mXc9wY-auronplay-me-pide-perd%C3%B3n-por-lo-que-me-hizo-en-2013-ya-est%C3%A1-todo-solucionado.html][img]https://i.ytimg.com/vi/AHTp6mXc9wY/hqdefault.jpg[/img][/url]

    Auronplay me pide perdГіn por lo que me hizo en 2013 (ya [url=https://dalasreview.alclip.info/AHTp6mXc9wY-auronplay-me-pide-perd%C3%B3n-por-lo-que-me-hizo-en-2013-ya-est%C3%A1-todo-solucionado.html]estГЎ[/url] todo solucionado)

    Reply
  16. [url=https://musicteam.top]скачать песни мп3 бесплатно[/url]

    Reply
  17. [url=https://newaudio.top]песни скачать бесплатно mp3[/url]

    Reply
  18. [url=https://godmp3.top]музыка mp3[/url]

    Reply
  19. [url=https://newmixtape.top]музыка 2021 без[/url]

    Reply
  20. [url=https://harrystylesvevo.mnwork.info/videos/BarDOBWuVg4-harry-styles-carolina-audio.html][img]https://i.ytimg.com/vi/BarDOBWuVg4/hqdefault.jpg[/img][/url]

    Harry Styles – Carolina [url=https://harrystylesvevo.mnwork.info/videos/BarDOBWuVg4-harry-styles-carolina-audio.html](Audio)[/url]

    Reply
  21. [url=https://allmp3.top]белым бела песня[/url]

    Reply
  22. [url=https://webmusic.top]качество mp3[/url]

    Reply
  23. [url=https://smtown.eswindow.info/i56Zqaei2H2bm30/aespa-eseupa.html][img]https://i.ytimg.com/vi/ZeerrnuLi5E/hqdefault.jpg[/img][/url]

    Aespa м—ђмЉ¤нЊЊ [url=https://smtown.eswindow.info/i56Zqaei2H2bm30/aespa-eseupa.html]‘Black[/url] Mamba’ MV

    Reply
  24. [url=https://aageeth88.padesk.info/oIjSZ4LXkH1xxa8/greatest-cricket][img]https://i.ytimg.com/vi/jOn1Pv-KAcI/hqdefault.jpg[/img][/url]

    GREATEST CRICKET [url=https://aageeth88.padesk.info/oIjSZ4LXkH1xxa8/greatest-cricket]MATCH[/url] IN THE WORLDCricket Series Part 2

    Reply
  25. [url=https://cricketicc.padesk.info/e4iamZjLmZiX25o/plucked-out][img]https://i.ytimg.com/vi/EO6cfj6fgy4/hqdefault.jpg[/img][/url]

    Plucked out of the airClassic c&bBowlers [url=https://cricketicc.padesk.info/e4iamZjLmZiX25o/plucked-out]Month[/url]

    Reply
  26. [url=https://retinageneric.com/]can you buy tretinoin cream over the counter[/url] [url=https://tadalafilsuper.com/]tadalafil 5mg canada[/url]

    Reply
  27. [url=https://smtown.usdos.info/let-s-make-smtown-live-tickets-with-superjunior-syupeojunieo-wa-tikku/v2t5pX-yptx4iqs][img]https://i.ytimg.com/vi/Y5EpLyAyCTs/hqdefault.jpg[/img][/url]

    рџЋџ Let’s make SMTOWN LIVE TICKETS with [url=https://smtown.usdos.info/let-s-make-smtown-live-tickets-with-superjunior-syupeojunieo-wa-tikku/v2t5pX-yptx4iqs]#SUPERJUNIORрџЋ«[/url] #мЉ€нЌјмЈјл‹€м–ґ м™Ђ н‹°кѕё

    Reply
  28. [url=https://1xbettv.ruworld.info/ks-barselona-uvolila-val-verde-kotoryj-vyigral-superkubok-ispanii-takoj-vot-s-r/k5W6jmGCzKyiqWU][img]https://i.ytimg.com/vi/0bWX1KisjG0/hqdefault.jpg[/img][/url]

    РљРЎ Барселона уволила [url=https://1xbettv.ruworld.info/ks-barselona-uvolila-val-verde-kotoryj-vyigral-superkubok-ispanii-takoj-vot-s-r/k5W6jmGCzKyiqWU]Вальверде[/url] , который выиграл Суперкубок Испании. Такой РІРѕС‚ СЃСЋСЂ…

    Reply
  29. [url=https://kamagragn.com/]kamagra oral jelly cvs[/url]

    Reply
  30. [url=https://cashadvs.com/]need a loan with bad credit[/url]

    Reply
  31. [url=https://szczypsongames.plthrow.info/sta-em-si/2KZmhXqYy6uOi6s.html][img]https://i.ytimg.com/vi/sq6UH3gEXYw/hqdefault.jpg[/img][/url]

    Stałem SIĘ [url=https://szczypsongames.plthrow.info/sta-em-si/2KZmhXqYy6uOi6s.html]DZIEWCZYNĄ[/url] w Minecraft straszne

    Reply
  32. [b][url=https://novostroyka63.ru/]Бетонный фундамент цена[/url][/b]

    Создание дома вашей мечты – это оригинальная возможность, спланировать и претворить в жизнь нечто воистину уникальное во всех отношениях. Возведение фундамента – это в целом первоначальная модель ремонта, в процессе которой домик строится. При расчете замена фундамента под старым деревянным домом цена предусматривается весьма много факторов. Средняясумма возведения домов фундамента составляет приблизительно от 10$ за кв.метр . Погреб сможет умножить итоговую стоимость каждого объекта недвижимости, предоставляя необходимое помещение ради организации хранения и порой рабочее пространство. Наша профессиональная команда по конструированию и возведенью фундамент под памятник на кладбище цена может помочь выстроить жилище, о котором вы всегда мечтали. От начала до конца наша специализированная компания в Череповец позаботимся о всех без исключения процессах, чтобы заказчику не довелось тревожиться о деталях. Специализированная международная компания в Киселевск несет юридическую ответственность за проект, а не вы, именно поэтому организация в Борисоглебск имеют интерес в том, затем чтобы довести до конца строительство коттеджа быстрее и эффективнее. Узнайте о сваи винтовые для фундамента цены в вытегре у спспециалистовециалистов корпорации.

    Reply
  33. [url=https://oursongs.xyz]песни онлайн[/url]

    Reply
  34. [url=https://llebof.frlifes.info/message-important/c9OvnH-Yt6WBq5I][img]https://i.ytimg.com/vi/CpxiHhUtIGY/hqdefault.jpg[/img][/url]

    [url=https://llebof.frlifes.info/message-important/c9OvnH-Yt6WBq5I]MESSAGE IMPORTANT[/url]

    Reply
  35. [url=https://songbeat.xyz]песня самая самая[/url]

    Reply
  36. [url=https://wildsong.xyz]слушать музыку новинки[/url]

    Reply
  37. [url=https://themp3.xyz]лучший песнь[/url]

    Reply
  38. [url=https://thehypercraftt.uzload.info/a5yVo53YyGykyGg/eating-only.html][img]https://i.ytimg.com/vi/6i_plrf3pc8/hqdefault.jpg[/img][/url]

    Eating Only Viral TIKTOK Food For 24 Hours [url=https://thehypercraftt.uzload.info/a5yVo53YyGykyGg/eating-only.html]-[/url] Challenge

    Reply
  39. [url=http://chloroquineactive.com/]chloroquine cost canada[/url] [url=http://oralkamagra.com/]kamagra oral jelly amazon[/url]

    Reply
  40. [url=https://fluoxetinesri.com/]10mg fluoxetine[/url]

    Reply
  41. [url=https://ivermectinoverthecounter.com/]stromectol tab 3mg[/url]

    Reply
  42. [url=https://oralkamagra.com/]kamagra oral jelly 100mg price in india[/url] [url=https://optadalafil.com/]tadalafil 30 mg[/url] [url=https://chloroquineactive.com/]malarex[/url] [url=https://cipromed.com/]ciprofloxacin 500mg[/url] [url=https://ivermectinoverthecounter.com/]ivermectin 0.08 oral solution[/url]

    Reply
  43. [url=https://mp3hit.xyz]песнь песней скачать бесплатно[/url]

    Reply
  44. [url=https://musbeat.xyz]нова песня[/url]

    Reply
  45. Это — здорово!


    Что-то меня уже не на ту тему понесло. скачать фифа, скачать фифа и [url=http://15fifa.ru/]fifa 15[/url] скачать fifa

    Reply
  46. Vladimirxfr

     /  2021/01/27

    удалите,пожалуйста! [url=https://spam-rassylka.ru/].[/url]

    Reply
  47. [url=https://mp3map.xyz]песня давай давай даю даю[/url]

    Reply
  48. Прошу прощения, ничем не могу помочь. Но уверен, что Вы найдёте правильное решение.


    Ваша мысль блестяща скачать fifa, скачать fifa или [url=http://15fifa.ru/]fifa 15[/url] скачать fifa

    Reply
  49. [url=https://usemusic.xyz]музыка онлайн 2020[/url]

    Reply
  50. [url=https://skymusic.xyz]лучшие песни слушать онлайн[/url]

    Reply

Leave a Reply