In this tutorial, we will be creating a webserver from scratch using python. For this program we will be using sockets as our primary building block.
First, let’s a file main.py and insert the code below.
import socket
class WebServer:
def __init__(self, host='', port=8080):
self.host = host
self.port = port
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def start(self):
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(1)
print(f'Server started on port {self.port}...')
while True:
conn, addr = self.server_socket.accept()
with conn:
request = conn.recv(1024).decode()
if not request:
continue
lines = request.split('\n')
method, path, protocol = lines[0].split(' ')
print(f'Received request from {addr[0]}: {request.strip()}')
if method == 'GET':
if path == '/':
response = 'HTTP/1.1 200 OK\nContent-Type: text/html\n\n<h1>Welcome to my web server!</h1>'
else:
response = 'HTTP/1.1 404 Not Found\nContent-Type: text/html\n\n<h1>404 Not Found</h1>'
else:
response = 'HTTP/1.1 405 Method Not Allowed\nContent-Type: text/html\n\n<h1>405 Method Not Allowed</h1>'
conn.sendall(response.encode())
if __name__ == '__main__':
server = WebServer()
server.start()
Run the main.py and a webpage should be available as shown below.
There you have it, Thanks for reading. Happy Coding