create a http server on a specific port in python

Here's an example of how to create an HTTP server on a specific port in Python using the socket module:

main.py
import socket

HOST = '127.0.0.1'  # Localhost
PORT = 8000

# Create a TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific address and port
server_socket.bind((HOST, PORT))

# Listen for incoming connections
server_socket.listen(1)

print(f'Server listening on port {PORT}')

while True:
    # Wait for a connection
    connection, client_address = server_socket.accept()

    try:
        print(f"Client connected: {client_address}")

        # Receive the data from the client
        data = connection.recv(1024)

        # Send the HTTP response header
        response_header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
        connection.send(response_header.encode())

        # Send the HTML content
        response_body = "<html><body><h1>Hello, world!</h1></body></html>"
        connection.sendall(response_body.encode())

    finally:
        # Clean up the connection
        connection.close()
981 chars
38 lines

This code creates a TCP/IP socket and binds it to a specific address and port (127.0.0.1:8000 in this case). It then listens for incoming connections, and for each connection it receives, it sends an HTTP response header and content back to the client. The code will run indefinitely until you stop it manually or an error occurs.

gistlibby LogSnag