Lab Report: University of Dhaka
Lab Report: University of Dhaka
Lab Report: University of Dhaka
Lab Report
Title: Implementing File transfer using
Socket Programming and HTTP GET/POST
requests
Mohammad Asif
Roll: 54
and
Jannatin Tajri
Roll: 42
Submitted to:
Dr. Md. Abdur Razzaque
Dr. Muhammad Ibrahim
Dr. Md. Redwan Ahmed Rizvee
Dr. Md. Mamun Or Rashid
1.1 Objectives
The primary objectives of this laboratory experiment are twofold. Firstly,
to gain a comprehensive understanding of the foundational principles of
Socket Programming, including the creation and utilization of sockets for
efficient data transfer between networked systems. Participants will focus
on implementing a file transfer system using Socket Programming, delving
into the intricacies of establishing reliable communication channels and
facilitating the exchange of files between a server and a client. Secondly, the
experiment aims to explore the fundamentals of HTTP, with specific
emphasis on the GET and POST request methods. Participants will then
implement a file transfer mechanism utilizing these HTTP methods,
scrutinizing the higher-level abstraction they provide compared to Socket
Programming. Furthermore, the experiment entails a comparative analysis
of the strengths, weaknesses, and practical implications of file transfer
mechanisms implemented through Socket Programming and HTTP
GET/POST requests. This comparative evaluation will enable participants
to discern the suitability of each approach for different scenarios, ultimately
2
providing practical insights into the underlying principles of network
communication, file transfer protocols, and HTTP methods, thereby
facilitating informed decision-making for specific application requirements.
2 Theoritical Background
2.1 Socket Programming
Socket Programming serves as a foundational concept in network
communication, enabling processes on different devices to establish
communication channels. A socket acts as an endpoint for sending or
receiving data across a network, facilitating seamless communication using
protocols like TCP or UDP. Key steps in Socket Programming include
socket creation, binding to an address and port, listening for incoming
connections (for server applications), and establishing connections (for
client applications). Understanding these principles provides insight into
the low-level details of data exchange between networked systems.
3
approach, ideally suited for web-based applications, boasting simplicity and
interoperability as its hallmarks. The analysis aims to delineate the
strengths and weaknesses of each method, taking into account factors such
as efficiency, implementation ease, and suitability for diverse scenarios.
This theoretical foundation empowers participants to assess trade-offs
between the two approaches and make informed decisions tailored to
specific application requirements.
By delving into these theoretical underpinnings, participants will attain a
thorough comprehension of Socket Programming and HTTP principles,
paving the way for the practical implementation and juxtaposition of file
transfer mechanisms in subsequent segments of the laboratory experiment.
3 Methodology
The execution of file transfer mechanisms via Socket Programming and
HTTP GET/POST requests necessitates a systematic approach to ensure a
comprehensive grasp of the underlying concepts and their practical
implementation. The following methodology delineates the essential steps
of the laboratory experiment:
4
3. HTTP GET/POST Implementation:
• Design and implement client-side scripts to send GET requests for file
retrieval and POST requests for file uploads.
4. File Preparation:
• Create sample files intended for testing the file transfer mechanisms.
• Run the Socket Programming scripts on both the server and client
systems.
6. Comparative Analysis:
5
1. Implement a simple file server that listens for incoming connections
on a specified port. The server should be able to handle multiple
clients simultaneously.
2. When a client connects to the server, the server should prompt the
client for the name of the file they want to download.
3. The server should then locate the file on disk and send it to the client
over the socket.
4. Implement a simple file client that can connect to the server and
request a file. The client should save the file to disk once it has been
received.
Server.py Code
import socket
import threading
import os
def handle_client(client_socket):
client_socket.send("Enter the name of the file you want to download: ".en
file_name = client_socket.recv(1024).decode()
#locate the file on the disc
file_path = os.path.join("files", file_name)
if os.path.exists(file_path):
with open(file_path, "rb") as file:
file_content = file.read()
client_socket.send(file_content)
else:
client_socket.send("File not found".encode())
client_socket.close()
6
server.listen(5)
while True:
client,addr=server.accept()
print(f"Accepted connection from {addr}")
client_handler=threading.Thread(target=handle_client,args= (client,))
client_handler.start()
Client.py Code
import socket
def file_client():
client=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostbyname(socket.gethostname())
client.connect((host,12341))
prompt=client.recv(1024).decode()
print(prompt)
client.send(file_name.encode())
file_content=client.recv(1024)
else:
print("File not found on the server.")
7
client.close()
file_client()
Experimental Result
The provided Python code establishes a server for file transfer using
sockets. Here’s a breakdown of the key components:
The provided Python client code connects to the server and initiates
the file transfer process. Here’s a breakdown of the key components:
8
• File Retrieval: Upon successful connection, the client receives
the file name and size from the server and prompts the user
whether to continue with the file transfer.
• User Choice: The user can choose whether to proceed with the
file transfer by entering ’y’ or cancel the transfer by entering ’n’.
• File Transfer: If the user chooses to continue, the client receives
the file in chunks and writes them to the local file system. The
client displays progress information during the transfer.
• Disconnection: After the file transfer is complete or cancelled,
the client closes the connection to the server and exits.
(a) Implement a simple HTTP file server that listens for incoming
connections on a specified port. The server should be able to
handle multiple clients simultaneously.
(b) When a client sends a GET request to the server with the path
of the file they want to download, the server should locate the
file on disk and send it to the client with the appropriate HTTP
response headers. The client should save the file to disk once it
has been received.
(c) When a client sends a POST request to the server with a file, the
server saves it.
9
Server.py Code
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
class FileServer(BaseHTTPRequestHandler):
def do_get(self):
try:
file_path=self.path[1:]
if os.path.exists(file_path):
with open(file_path,"rb") as file:
file_content = file.read()
self.send_response(200)
self.send_header("Content-type","application/octet-stream
self.end_headers()
self.wfile.write(file_content)
else:
self.send_response(404)
self.end_headers()
self.wfile.write(b"File not found")
except Exception as e:
self.send_response(500)
self.end_headers()
self.wfile.write(f"Server error: {str(e)}".encode())
def do_post(self):
try:
content_length=int(self.headers[’Content-length’])
file_content=self.rfile.read(content_length)
10
self.send_response(500)
self.end_headers()
self.wfile.write(f"server error: {str(e)}".encode())
def run_server(port=12345):
server_address=(’’,port)
httpd=HTTPServer(server_address, FileServer)
print(f"HTTP server running on port {port}")
httpd.serve_forever()
if name == "main":
run_server()
Client.py Code
mport requests
import os
import socket
host = socket.gethostbyname(socket.gethostname())
url = f"http://{host}:12345/C:/Users/tajri/PycharmProjects/lab"
def get_file(file_name):
response = requests.get(f"{url}/{file_name}")
if response.status_code == 200:
with open("downloaded_file", "wb") as file:
file.write(response.content)
print("File downloaded successfully.")
else:
print("Error:", response.text)
def post_file(file_path):
with open(file_path, "rb") as file:
files = {’file’: file}
response = requests.post(url, files=files)
11
if response.status_code == 200:
print("File uploaded successfully.")
else:
print("Error:", response.text)
def main():
while True:
print("Choose an option:")
print("1. GET file")
print("2. POST file")
print("3. Exit")
option = input("Enter your choice: ")
if option == "1":
file_name = input("Enter the name of the file to download: ")
get_file(file_name)
elif option == "2":
file_path = input("Enter the path of the file to upload: ")
post_file(file_path)
elif option == "3":
print("Exiting...")
break
else:
print("Invalid option. Please try again.")
if name == "main":
main()
Experimental Result
The provided FastAPI server code establishes an HTTP server
capable of handling file uploads and downloads. Here’s a
breakdown of the key components:
• Root Endpoint: The root endpoint (”/”) returns a simple
response indicating the server’s status.
12
• Download Endpoint: The ”/download/fileName”
endpoint allows clients to download files by specifying the
desired file name.
• Upload Endpoint: The ”/upload” endpoint handles file
uploads. Clients can upload files, and the server saves them
to the local file system.
• List Endpoint: The ”/list” endpoint provides a list of all
uploaded files on the server.
The server is designed to be accessible via any web browser,
including local browsers. Users can upload files, download them,
and view the list of available files.
13
• List Files: The client retrieves and displays the list of
available files on the server.
• Upload File: The client uploads a file to the server by
specifying the file path. The file is transmitted to the server
and stored in the local file system.
The client code provides a user-friendly, interactive interface for
file operations with the FastAPI server. Users can choose to
download, list, or upload files based on their preferences. Further
enhancements could include robust error handling, improved
user experience, and additional features.
14