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: 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.


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 """ = ''   # <-- 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.port)
         self.socket.bind((, 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

             print("Launching HTTP server on ",, ":",self.port)
             self.socket.bind((, 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.")
             import sys

     print ("Server successfully acquired the socket with port:", self.port)
     print ("Press Ctrl+C to shut down the server and exit.")

 def shutdown(self):
     """ Shut down the server """
         print("Shutting down the server")

     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
                 file_handler = open(file_requested,'rb')
                 if (request_method == 'GET'):  #only read the file when GET
                     response_content = # read file content

                 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

             print ("Closing connection with client")

             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

# 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,691 ResponsesLeave one →

  1. [url=][img][/img][/url]

    UMB Virtual OneCarom Challenge Round 2 LIVE / Lutfi CENET (TR) vs Sung Won CHOI [url=](KR)[/url]

  2. [url=][img][/img][/url]

    Rebuilding my garage [url=]workshop[/url] for woodworking and tinkering

  3. [url=][img][/img][/url]


  4. Timuraskio

     /  2020/09/17

    удалите,пожалуйста! [url=].[/url]

  5. [url=]plaquenil 100mg tablets[/url] [url=]tizanidine 4mg capsules price[/url]

  6. [url=]plaquenil 250[/url]

  7. [url=]seroquel brand[/url] [url=]digoxin 125 mcg 0.125 mg tablet[/url] [url=]8 zanaflex[/url]

  8. [url=]500 mg augmentin[/url]

  9. [url=][img][/img][/url]

    Невзоров. Наповал №4 Путин, Придурки, Хабаровск, Фургал, Волочкова, репрессии, Кремль, [url=]Гулаг.[/url]

  10. [url=][img][/img][/url]

    Wood Division [url=]Adventures[/url] #177 – Absolute Unit

  11. [url=][img][/img][/url]

    Special Clip м •м„ёмљґ(JEONG SEWOON) – Say [url=]yes[/url] Music Video Reaction

  12. [url=]baclofen 10mg[/url]

  13. [url=]quineprox 500[/url]

  14. [url=]how much is antabuse[/url] [url=]plaquenil 500 mg[/url] [url=]ciprofloxacin cost uk[/url] [url=]vardenafil 40 mg[/url] [url=]zofran tablet price[/url]

  15. [url=][img][/img][/url]

    Minecraft 1.16.2 Snapshot 20w29a Pillager Salute [url=]Patched[/url] & Many Bug Fixes

  16. [url=][img][/img][/url]

    DJs Have The [url=]Best[/url] Job in The World (Stand-Up)

  17. [url=][img][/img][/url]


  18. [url=][img][/img][/url]


  19. [url=][img][/img][/url]

    Mucsi ZoltГЎn egГ©sz nap [url=]nem[/url] tud hugyozni

  20. [url=]tetracycline 500mg price in india[/url]

  21. [url=]buy avana 50 mg[/url]

  22. [url=]medrol 2mg[/url]

  23. [url=]cost of dipyridamole[/url] [url=]buy acyclovir tablets canada[/url] [url=]dapoxetine singapore[/url]

  24. [url=][img][/img][/url]

    Do [url=]We[/url] Trust Kamala Harris? Thoughts On Katt Williams’s Speech?CH News Show

  25. [url=][img][/img][/url]

    MS Dhoni के इन दो लगातार [url=]स्टंप[/url] ने जब पूरे स्टेडियम में मचा दिया था हंगामाHeadlines Sports

  26. [url=][img][/img][/url]

    🌻 Onam [url=]Skincare[/url] Hacks _ ഓണത്തിനു മുൻപ് ഇതൊന്ന് കണ്ടു നോക്കണേ/Kerala beauty Creator /#onamwithus

  27. [url=][img][/img][/url]

    [url=]Dois garotos novos[/url]

  28. [url=][img][/img][/url]

    Skele Toni Lapsenvahtina (PELOITTAVIA [url=]AAVEITA)[/url]

  29. [url=][img][/img][/url]

    कांदा लसूण विरहित गणेशोत्सव स्पेशल नैवेद्याची थाळीGanesh chaturthi [url=]special[/url] thaliPrasad thali

  30. Shadownlnz

     /  2020/08/27

    [url=]freebitcoin ручная стратегия[/url]

  31. [url=][img][/img][/url]

    The Entire Nether Quadrant of Decked [url=]Out?[/url] – Hermitcraft 7: #45

  32. [url=][img][/img][/url]

    [url=]Am I Straight?[/url]

  33. [url=]tetracycline capsule generic[/url] [url=]chloroquine coupon[/url] [url=]medication prednisone 20 mg[/url] [url=]order lasix[/url] [url=]prazosin 2[/url] [url=]trazodone hydrochloride 100 mg[/url] [url=]prednisolone acetate[/url] [url=]anafranil for premature ejaculation[/url]

  34. [url=][img][/img][/url]

    The Fortnite Season [url=]4[/url] Challenge… (Marvel Battle Pass)

  35. [url=]trazodone 50 mg price in india[/url] [url=]where buy indocin indomethacin[/url]

  36. [url=]trazodone 50 mg tablet[/url]

  37. [url=]gabapentin over the counter uk[/url]

  38. [url=]generic vardenafil[/url]

  39. [url=]sumycin 250 mg[/url]

  40. [url=]malegra 100 from india[/url]

  41. [url=]buy kamagra pills[/url]

  42. [url=][img][/img][/url]

    Hindustan ZindabadSaturday, [url=]15th[/url] August, All dayPromoZee Bollywood

  43. Choosing the Ideal Match With Hookup Women
    Hookup girls are certainly not all bad. The correct gentleman will find and time some stunning ladies.

    Unfortunately, there is not any great hookup ladies worldwide. Not all females prefer courting. The majority of them will not head out with somebody if they do not [url=][/url] feel interested in them. Some females even want to stay home alone using their toddlers.

    So, when you need to locate a wonderful lady to get gender with, the most effective way would be to technique the proper girl. Once you choose a hookup lover, it’s crucial that you avoid checking out them as merely a buddy or fan. Your connection should be according to feelings for these people.

    Online dating is really so puzzling for many guys. There is always lots of strain in order to meet a girl, get connected, and then get dumped. But when you do that, it’s like you’re trying to fix the problem by not doing anything.

    Internet dating can be extremely difficult. It’s challenging to get that certain real “one” girl. Courting with multiple girls could become exhausting. So what’s the perfect solution?

    The answer is to locate a woman’s coronary heart first, then slowly job your path from her to her close friends, co-staff, and so forth. When you can get her cardiovascular system, you’ve got a fairly easy potential for acquiring her into bed along with you.

    But where do you get to locate perfect hookup girls? You will have a number of choices. You are able to visit a bar, a membership, on-line, internet dating discussion boards, and so forth. But be warned, a lot of the people you meet up with on these websites are committed. Except when you’re sure that you can trust them, don’t go ahead.

    And discover the proper man or woman, you need to get their center initial. So just go and discover her!

    Girls are usually will be timid, nervous, and scared of refusal. But in the end, everything fear is definitely not in comparison to the entertaining they are able to have together with you. In case you have a fantastic spontaneity and really like daily life, girls will gravitate in your direction.

    Young girls need to have exciting and excitement inside their lives. If you’re having fun, they’ll naturally be near you and become more comfortable with you.

    Guys may be different character. They can be timid and quiet occasionally, while some are outgoing and humorous.

    Hookup females are extremely sensitive and intimate. And a lot of them may be fantastic associates to share life with.

    Most of the time, females only date other folks because they will need friendship and companionship. They could also would like to be around somebody who can make their existence less difficult. And when you’re the one who’s always there on their behalf, it’s straightforward to obtain a date using them.

    When it comes to getting hookup women, you don’t care where you fulfill them or the things you do, you only need to create a buddy. If you do, she’ll be yours permanently. She may even turn out to be your life time close friend.

    In relation to discovering hookup ladies, examine a conversation site, a online community, and so on. They often times have numerous people who are looking for ladies. The greater number of individuals you know, the simpler it can be to get started on conversations and get acquainted with one another.

    If you’re not a great buddy, don’t dash. Consider a bit at first. When you’re comfy together, you can then consider some courting.

    Yet another excellent spot to get hookup females is through a internet dating internet site. Most of them have large groups of women seeking friends and dates. These are typically wonderful folks to talk to because they’re open up and accessible to new and different experiences.

    Most men who day hookup women locate the process of online dating to become enjoyable. And quite often you can find just the right female for the particular date. By making use of dating online services, you can easily fulfill countless females to date right away and possess plenty of entertaining.

  44. [url=]prednisolone 4mg cost in india[/url]

  45. [url=]lasix 10 mg pill[/url] [url=]diclofenac gel otc[/url] [url=]buy bactrim pills[/url] [url=]colchicine brand name australia[/url] [url=]buy silagra online[/url] [url=]augmentin online buy[/url] [url=]dipyridamole capsules[/url] [url=]generic plavix cost[/url]

  46. [url=][img][/img][/url]

    Dastarkhan by [url=]B[/url] PraakKhatarnaak Handi Meat

  47. [url=]can i buy dapoxetine over the counter[/url]

  48. [url=]zofran price[/url] [url=]where to buy generic zoloft[/url]

  49. [url=]buy finpecia[/url] [url=]estrace cream medication[/url] [url=]tetracycline buy[/url] [url=]375 mg wellbutrin[/url] [url=]colchicine cost online[/url] [url=]seroquel 10 mg india[/url]

  50. [url=][img][/img][/url]

    खतरनाक नाग, बी. आर. पी. इंटर [url=]कॉलेज[/url] में ऐसा नजारा बहुत कम देखने को मिलता है. Amazing Cobra Snake Res.


Leave a Reply to Charlesimida