Computer Networks Assigment-3
Computer Networks Assigment-3
B210688EC
EC01
EC3022D Computer
Networks Winter Semester
2023-24
Question:
Build a Web Server in C/Python using Socket programming. The web server
should be able to respond to simple HTTP commands like GET, POST etc.
When a GET request is sent, the server should respond with a page containing
your name and roll number.
Code:
At the web server:
# server.py
1
import socket
2
3
def handle_request(request):
4
if request.startswith("GET"):
5
return "HTTP/1.1 200 OK\nContent-Type: text/html\n\n<html><body><h1>Computer Networks
6
Assignment-2</h1> <br> <h2>Name: Balabhadra Niketh<br>Roll Number: B210688EC</h2>" \
7
"</body></html>"
8
else:
9
return "HTTP/1.1 501 Not Implemented\nContent-Type: text/plain\n\nNot Implemented"
10
11
def start_server(host, port):
12
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13
server_socket.bind((host, port))
14
server_socket.listen(5)
15
print(f"Server listening on {host}:{port}")
16
17
while True:
18
client_socket, client_address = server_socket.accept()
19
print(f"Client connected from {client_address}")
20
request_data = client_socket.recv(1024).decode()
21 print(f"Request received:\n{request_data}")
22 response = handle_request(request_data)
23 client_socket.sendall(response.encode())
24 client_socket.close()
25
26 if name == " main ":
27 HOST = '127.0.0.1' # Localhost
28 PORT = 8080
29 start_server(HOST, PORT)
Balabhadra Niketh
B210688EC
EC01
Block Diagram at Webserver:
Function Calls:
Send Request : The client sends an HTTP request to the server specifying the host
and port using socket.connect() and socket.sendall().
Receive Response : The client waits to receive the response from the server using
socket.recv().
Print Response : Upon receiving the response, the client prints it to the console.
Balabhadra Niketh
B210688EC
EC01
Webpage output :
Conclusion:
The server efficiently manages incoming HTTP requests by processing them according to
their type and generating suitable responses. Meanwhile, the client effectively sends requests
to the server and receives and prints the responses it receives. This interaction exemplifies a
fundamental client-server architecture, where the server listens for connections, handles
request processing, and sends responses. On the other hand, the client initiates requests and
manages the received responses accordingly, forming a cohesive communication model
between the two entities. This architecture facilitates seamless communication and resource
sharing between clients and servers in distributed systems