Cnlab52021 Ce 40

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Name: ………Ali Abdullah……..

Registration No: ………2021-CE-40…………………

Date: ………5-03-2024…………………….. Grade and Signature: ………………………..

Course Name: Computer Networks Course Code: CMPE-333L

Assignment Type: Lab Dated: 29-02-2024

Semester: 6th Session: 2021-2025

Lab #: 5 CLOs to be covered: 2,3

Lab Title: Web Server using Socket Programming Teacher Name: Darakhshan Abdul Ghaffar

Lab Evaluations:
CLO2, CLO3 Analyze the Internet core functions using diverse online available
tools Build simulations to measure the network parameters

Levels (Marks) Level1 Level2 Level3 Level4 Level5 Level6

Completeness
(5)

Total /10

Rubrics for Current Lab (Optional):


Scale Marks Level Rubric

Excellent 10 L1 Submitted all lab tasks during the lab, have


good understanding.

Very Good 8 L2 Submitted the lab tasks but have weak understanding

Good 6 L3 Submitted the lab tasks but have weak understanding.

Basic 4 L4 Submitted the lab tasks but have no understanding.

Barely 2 L5 Submitted only one lab task.


Acceptable
Running the Server
Python code :

#import socket module

from socket import *

import sys # In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a sever socket

#Fill in start

# Assign a port number

serverPort = 6789

# Bind the socket to the server address and port

serverSocket.bind(('', serverPort))

# Start listening to incoming connections

serverSocket.listen(1)

print('The server is ready to receive')

#Fill in end

while True:

#Establish the connection

print('Ready to serve...')

connectionSocket, addr = serverSocket.accept() #Fill in start #Fill in end

try:

message = connectionSocket.recv(1024).decode()

filename = message.split()[1]

f = open(filename[1:])

outputdata = f.readlines()

#Send one HTTP header line into socket

#Fill in start
connectionSocket.send('HTTP/1.1 200 OK\n\n'.encode())

#Fill in end

#Send the content of the requested file to the client

for i in range(0, len(outputdata)):

connectionSocket.send(outputdata[i].encode())

connectionSocket.close()

except IOError:

#Send response message for file not found

#Fill in start

connectionSocket.send('HTTP/1.1 404 Not Found\n\n'.encode())

#Fill in end

#Close client socket

#Fill in start

connectionSocket.close()

#Fill in end

serverSocket.close()

sys.exit()#Terminate the program after sending the corresponding data

Now, Test the server by this link http://10.5.98.94:6789/HelloWorld.html

And after testing: Real content of my HelloWorld.html file is shown on browser.


Lab Task
1. Currently, the web server handles only one HTTP request at a time. Implement a

multithreaded serverthat is capable of serving multiple requests simultaneously. Using

threading, first create a main threadin which your modified server listens for clients at

a fixed port. When it receives a TCP connection request from a client, it will set up the

TCP connection through another port and services the client request in a separate thread.

There will be a separate TCP connection in a separate thread for each request/response

pair.

Python code :

from socket import *

import sys

import threading
def handle_request(connectionSocket):

try:

message = connectionSocket.recv(1024).decode()

filename = message.split()[1]

f = open(filename[1:])

outputdata = f.readlines()

connectionSocket.send('HTTP/1.1 200 OK\n\n'.encode())

for i in range(0, len(outputdata)):

connectionSocket.send(outputdata[i].encode())

connectionSocket.close()

except IOError:

connectionSocket.send('HTTP/1.1 404 Not Found\n\n'.encode())

connectionSocket.close()

def main():

serverSocket = socket(AF_INET, SOCK_STREAM)

serverPort = 6789

serverSocket.bind(('', serverPort))

serverSocket.listen(5)

print('The server is ready to receive')

while True:

print('Ready to serve...')

connectionSocket, addr = serverSocket.accept()

t = threading.Thread(target=handle_request, args=(connectionSocket,))

t.start()

if name == " main ":

main()

Now, Test the server by this link on multiple browsers http://10.5.98.94:6789/HelloWorld.html


I found same and original content of my HelloWorld.html on multiple browsers

Bonus Task
2. Instead of using a browser, write your own HTTP client to test your server. Your client

will connectto the server using a TCP connection, send an HTTP request to the server,

and display the server response as an output. You can assume that the HTTP request

sent is a GET method.

The client should take command line arguments specifying the server IP address or host

name, the port at which the server is listening, and the path at which the requested object

is stored at the server. The following is an input command format to run the client.

client.py server_host server_port filename

Python code :

# BONUS TASK

# import socket

# hostname = socket.gethostname()

# print("Hostname:", hostname)

# ip_address = socket.gethostbyname(hostname)
# print("IP Address:", ip_address)

import socket

import sys

def http_get(server_host, server_port, filename):

# Create a socket for the client

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:

# Connect to the server

client_socket.connect((server_host, server_port))

# Send the HTTP GET request

request = f"GET /{filename} HTTP/1.1\r\nHost: {server_host}\r\n\r\n"

client_socket.sendall(request.encode())

# Receive the response from the server

response = client_socket.recv(4096)

# Display the server response

print(response.decode())

except socket.error as e:

print(f"Socket error: {e}")

finally:

# Close the client socket

client_socket.close()
if name == " main ":

if len(sys.argv) != 4:

print("Usage: client.py server_host server_port filename")

sys.exit(1)

server_host = sys.argv[1]

server_port = int(sys.argv[2])

filename = sys.argv[3]

http_get(server_host, server_port, filename)

Now TEST BY on command prompt : python client.py 10.5.98.94 6789 HelloWorld.html

And command prompt shows that request is successful and the server has returned the requested
content.

You might also like