LAB ASSIGNMENT : 3
Aim :- Web Server :
We will learn the basics of socket programming for TCP connections in
Python, how to create a socket, bind it to a specific address and port, as well as send and receive a HTTP packet. We will also learn some basics of HTTP header format.
Code :Below you will find the skeleton code for the Web server. You are to complete the skeleton code. The places where you need to fill in code are marked with #Fill in start and #Fill in end. Each place may require one or more lines of code.
Code in Python :#import socket module from socket import * serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill in start serverSocket.bind(('',8647)) serverSocket.listen(1)
#Fill in end while True:
#Establish the connection print 'Ready to serve...' connectionSocket, addr = serverSocket.accept() try: #Fill in start message = connectionSocket.recv(1024) if not message: continue #Fill in end filename = message.split()[1] print filename[1:] f = open(filename[1:]) outputdata = f.read()
#Send one HTTP header line into socket
#Fill in start headerLine = "HTTP/1.1 200 OK Content-type:text/html; charset=utf-8\n\n" connectionSocket.send(headerLine.encode()) print outputdata
#Fill in end
#Send the content of the requested file to the client for i in range(0, len(outputdata)): connectionSocket.send(outputdata[i]) connectionSocket.close() except IOError:
#Send response message for file not found
#Fill in start pass print "404 Not Found" connectionSocket.send("HTTP/1.1 404 Not Found\n\n")
#Fill in end
#Close client socket
#Fill in start connectionSocket.close() #Fill in end serverSocket.close() Output :-
Fig : 1- Skeleton Code ( with #Fill in Start and ##Fill in end ) written in
Python shell
Fig : 2- Running the Python Shell Code in Server local host :
( Server Ipv4 : 192.168.0.4 )
Fig : 3- HTML Page displayed on Server Local Host Ipv4 : 192.168.0.4
Fig : 4- After Accessing Welcome.Html Page from Another Host