0% found this document useful (0 votes)
255 views

Coen445 Lab4 Socket Programming

This document provides instructions for a lab assignment on socket programming with Python to create a basic web server. It explains that students will develop a web server that can handle one HTTP request at a time by accepting and parsing the request, retrieving the requested file, generating an HTTP response, and sending the response to the client. It includes skeleton code for the web server that students need to complete, and provides optional exercises to multithread the server or develop a basic HTTP client.

Uploaded by

BansIa Shobhit
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views

Coen445 Lab4 Socket Programming

This document provides instructions for a lab assignment on socket programming with Python to create a basic web server. It explains that students will develop a web server that can handle one HTTP request at a time by accepting and parsing the request, retrieving the requested file, generating an HTTP response, and sending the response to the client. It includes skeleton code for the web server that students need to complete, and provides optional exercises to multithread the server or develop a basic HTTP client.

Uploaded by

BansIa Shobhit
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10

COEN 445

Communication Networks and Protocols


Lab 4
SocketProgrammingwithPython:
WebServer
ClaudeFachkha

Introduction
Pythonisageneralpurpose,highlevelprogramminglanguagethatisusedinavariety
ofapplicationdomains.ThePythonlanguagehasaveryclearandexpressivesyntaxas
wellasalargeandcomprehensivelibrary.AlthoughPythonisoftenusedasa
scriptinglanguage,itcanalsobeusedinawiderangeofnonscriptingcontexts.Its
availableforallmajorOperatingSystems.Pythonisfreetouse,evenforcommercial
products,becauseofitsOSIapprovedopensourcelicense.

Notethatinthislab,theexplanationincludesPythonlanguageonly.However,
feelfreetouseanyprogramminglanguage(i.e.,Java,C++,etc.)tofinishthe
experiments.Theconceptofsocketprogrammingisthesameunderallplatforms.

1. Installing & Running Python


http://www.python.org/

HelloWorldProgram
RunthePythonShell
printhelloworld

1.1 Example of a Basic Python Program

2. Socket Programming Assignment 1


Web Server
Inthislab,youwilllearnthebasicsofsocketprogrammingforTCPconnectionsinPython:
howtocreateasocket,bindittoaspecificaddressandport,aswellassendandreceivea
HTTPpacket.YouwillalsolearnsomebasicsofHTTPheaderformat.
YouwilldevelopawebserverthathandlesoneHTTPrequestatatime.Yourwebserver
shouldacceptandparsetheHTTPrequest,gettherequestedfilefromtheserversfile
system,createanHTTPresponsemessageconsistingoftherequestedfileprecededby
headerlines,andthensendtheresponsedirectlytotheclient.Iftherequestedfileisnot
presentintheserver,theservershouldsendanHTTP404NotFoundmessagebacktothe
client.

2. Socket Programming Assignment 1


Web Server (Cont.)
Code
NextyouwillfindtheskeletoncodefortheWebserver.Youaretocompletetheskeleton
code.Theplaceswhereyouneedtofillincodearemarkedwith#Fillinstartand#Fillin
end.Eachplacemayrequireoneormorelinesofcode.

Running the Server


Put an HTML file (e.g., HelloWorld.html) in the same directory that the server is in. Run the server program.
Determine the IP address of the host that is running the server (e.g., 128.238.251.26). From another host,
open a browser and provide the corresponding URL. For example:
http://128.238.251.26:6789/HelloWorld.html
HelloWorld.html is the name of the file you placed in the server directory. Note also the use of the port
number after the colon. You need to replace this port number with whatever port you have used in the server
code. In the above example, we have used the port number 6789. The browser should then display the
contents of HelloWorld.html. If you omit ":6789", the browser will assume port 80 and you will get the web
page from the server only if your server is listening at port 80.
Then try to get a file that is not present at the server. You should get a 404 Not Found message.

2. Socket Programming Assignment 1


Web Server (Cont.)
Skeleton Python Code for the Web Server
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill in start
#Fill in end
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = #Fill in start #Fill in end
try:
message = #Fill in start #Fill in end
filename = message.split()[1]
f = open(filename[1:])
outputdata = #Fill in start #Fill in end
#Send one HTTP header line into socket
#Fill in start
#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
#Fill in end
#Close client socket
#Fill in start
#Fill in end
serverSocket.close()

2 Socket Programming Assignment 1


Web Server (Cont.)
OptionalExercises
1. Currently,thewebserverhandlesonlyoneHTTPrequestatatime.Implementamultithreaded
serverthatiscapableofservingmultiplerequestssimultaneously.Usingthreading,firstcreatea
mainthreadinwhichyourmodifiedserverlistensforclientsatafixedport.Whenitreceivesa
TCPconnectionrequestfromaclient,itwillsetuptheTCPconnectionthroughanotherportand
servicestheclientrequestinaseparatethread.TherewillbeaseparateTCPconnectionina
separatethreadforeachrequest/responsepair.
2. Insteadofusingabrowser,writeyourownHTTPclienttotestyourserver.Yourclientwill
connecttotheserverusingaTCPconnection,sendanHTTPrequesttotheserver,anddisplaythe
serverresponseasanoutput.YoucanassumethattheHTTPrequestsentisaGETmethod.
TheclientshouldtakecommandlineargumentsspecifyingtheserverIPaddressorhostname,the
portatwhichtheserverislistening,andthepathatwhichtherequestedobjectisstoredatthe
server.Thefollowingisaninputcommandformattoruntheclient.
client.pyserver_hostserver_portfilename

References
OnlineservicesComputerNetworking:ATopDownApproach,6/E
JamesF.Kurose,UniversityofMassachusetts,AmherstSeemoreat:KeithW.
Ross,PolytechnicUniversity,Brooklyn

Claude Fachkha
[email protected]

You might also like