We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 2
7124123, 12:28 AN [AP PT CodePrint| Print Code
2.| From socket izport *
2 | import sys
4 | serverSocket = socket(AF_INET, SOcK_STREA)
5 | # Prepare a sever socket
5 | serverPort = 6789 # You can use any available port, such as 8@ for HTTP
7 | serversocket.bind((’', serverPort))
8 | Serversocket. 1isten(2)
9 | while True:
12 | # Establish the connection
ni | print(*Ready to serve...)
32 | connectionsocket, addr = serverSocket.accept()
B
ul ty:
6 rnessage = connectionSacket .recy(1024) .cecode()
6 ‘ilenane = sessage.split()[1]
v # = open(Filenane[:])
B cutputdata = f.read()
» F.close()
»
a 4 Send one HTTP header Line into socket
2 connectionSocket. send("HITP/2.1 268 OX\r\n\r\n" .encede())
2B
™ 4 Send the content of the requested file to the client
2% for 1 in range(@, len(outputdata)):
26 connect ionSocket. send (outputdatal !] .encode())
2 connectionSocket..send("\r\n" -encode())
23
2» cconnectionSocket.close()
32 | except ToError:
a If the requested file is not found, sené a 404 Not Found response with a custom HTML message
2 not_found message = °°"
2 ‘
a chemb>
5 chead>
36
7
38 boey>
2
~”
a
2
a
“ connectionsocket.send(*HTTP/1.1 404 Not Found\n\n\r\n"-encode())
5 connectionSacket. send(not_found_nessage.encose())
«6 connectionsocket.close()
4a7 | serversocket.close()
a3 | sys.exit()
PDF document made with CodePrint org
Intpssteodoprintorg7128128, 12:25 AM [AP PT CodePrint| Print Code
1 | nport socket
2 | import sys
3
4 | def nttp_client(server_address, server_port, file_path):
5 4 Create a socket and connect to the server
6 client_socket = socket. socket (socket .AF_INET, socket. SOCK_STREAM)
7 client_socket. connect ((server_address, server_port))
a
9 4 Send the HTTP GET request
1» request = #°GET (File_path} HTTP/1.1\r\nHost: (server_address}\r\n\n\n"
u cLient_socket. send (request .encode())
2
B # Receive and display the server response
4 response = client_socket.recv(4096) .decode()
6 print("Server Response:\n", response)
6
v # Close the socket
1“ cLient_socket.close()
Fey
2 | if _name__ == "main
a if len(sys.argy) !
2 print("Usage: python http_client.py ")
2B sys.exit(1)
m
2% server_address = sys.argv(1]
% server_port = int(sys.arev[?])
2 file_path = sys.argv(3]
Py
2 http_client (server_address, server_port, file_path)
PDF document made with CodePrint org
Intpssteodoprintorg
n