Lecture 4 Create HTTP Web Server
Lecture 4 Create HTTP Web Server
This lecture presents how to build simple WebServer, that listens to port 8080 on address 127.0.0.1
You can use the lsof (List Open Files) command along with grep to find the process listening on port 8080 and then use the kill
command to terminate it. Here's the command you can use in unix terminal:
1 lsof -i :8080 | awk '{print $2}' | grep -Eo '[0-9]+' | xargs 'kill'
1. lsof -i :8080 : Lists all open files (including network connections) and filters for those involving port 8080.
2. awk '{print $2}' : Extracts the second column, which contains the process IDs (PIDs) of the processes.
3. xargs kill : Takes the PIDs and sends a kill command to terminate the associated processes.
This command will find and terminate any process listening on port 8080.
3. Sending a Response
1 while True:
2 # Accept incoming client connections
3 client_socket, client_address = server_socket.accept()
4 print(f"Accepted connection from {client_address[0]}:{client_address[1]}")
5
6 # Receive and print the client's request data
7 request_data = client_socket.recv(1024).decode('utf-8')
8 print(f"Received Request:\n{request_data}")
9
10 # Prepare and send a simple HTTP response
11 response = "HTTP/1.1 200 OK\nContent-Type: text/html\n\nHello, World!"
12 client_socket.send(response.encode('utf-8'))
13
14 # Close the client socket
15 client_socket.close()
The web server gradually evolves from simply listening for connections to handling requests, sending responses, and adding signal
handling for graceful server shutdown. It's important to note that this is a simplified example for educational purposes and lacks many
features of a production-ready web server.
3. The response_content variable holds the content that will be sent in the HTTP response.
4. We've modified the response line to include the status code and provide a content type header.
5. In the handle_request function, if the requested path is not found, it responds with a "404 Not Found" message and sets the status
code accordingly.
Now, your server includes basic routing and handles 404 errors gracefully.