How to write a simple web server

In this post you will learn how to write a simple web server using python language. I have put up the code here and you can refer the comments in the code to learn what each code does.

#imports the socket which works as end points of a tunnel

import socket

#here host name and port number is fed into the program using python inputs

HOST_NAME = ”
PORT_NUMBER = 8888

# server address is made out of host name and port number

MY_SERVER_ADDRESS=HOST_NAME,PORT_NUMBER

#this shows how many requests can be taken at a time

MY_REQUEST_QUEUE_SIZE=5

def serve_me_forever():

# the below two lines describes the type of the socket we need

listen_socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET , socket.SO_REUSEADDR , 1)
listen_socket.bind(MY_SERVER_ADDRESS)
listen_socket.listen(MY_REQUEST_QUEUE_SIZE)
print (‘Serving HTTP on port number {port} …’ .format(port=PORT_NUMBER))

while True:
client_connection, client_address = listen_socket.accept()

# here 1024 means the size of the request(bytes)

request = client_connection.recv(1024).decode()

print (request)
try:
my_path=request.split(‘ ‘)[1]
except:
pass
print (my_path)
if my_path==’/’:

#this is the header of the request
client_connection.send(‘HTTP/1.1 200 OK\r\n’)

# Content-Type can be text/css,text/png etc.

client_connection.send(‘Content-Type:text/html\r\n\r\n’)
my_file=open(‘ucsc.html’)
client_connection.send(my_file.read())

elif my_path.endswith(‘.png’):
client_connection.send(‘HTTP/1.1 200 OK\r\n’)
client_connection.send(‘Content-Type:image/png\r\n\r\n’)
my_file=open(my_path[1:], ‘rb’)
client_connection.send(my_file.read())

else:

# the blank line between the header and body is compulsory

client_connection.send(‘HTTP/1.1 404 Not Found\r\n’)
client_connection.send(‘Content-Type:text/html\r\n\r\n <h1>404 Page Not Found</h1>’)

client_connection.close()

serve_me_forever()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s