'How to enable a python multithreading server to run on localhost and receive html files?

I'm currently working on a multithreaded web server in Python which should be capable of processing HTTP requests sent from a browser or any other client programs.

I have a client.py file and a server.py file. Right now, I can run both of them on separate terminals and send messages from the client to the server.

What I want to do is to host the server on a localhost and send HTML files from the client to the server, so that the HTML files can be displayed on the server - hence on the localhost site. The server and client codes are down below. Help would be highly appreciated.

Thanks in advance!

Server.py -

import socket
import threading

IP = socket.gethostbyname(socket.gethostname())
PORT = 5566
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
DISCONNECT_MSG = "!DISCONNECT"


def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
        msg = conn.recv(SIZE).decode(FORMAT)
        if msg == DISCONNECT_MSG:
            connected = False

        print(f"[{addr}] {msg}")
        msg = f"Msg received: {msg}"
        conn.send(msg.encode(FORMAT))

    conn.close()


print("Server is starting...")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen()
print(f"Server is listening on {IP}:{PORT}")

while True:
    conn, addr = server.accept()


    try: 
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}")

    except IOError:
        conn.send('\nHTTP/1.1 404 Not Found\n\n'.encode())
        conn.close()

Client.py -

import socket

IP = socket.gethostbyname(socket.gethostname())
PORT = 5566
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
DISCONNECT_MSG = "!DISCONNECT"


client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
print(f"[CONNECTED] Client connected to server at {IP}:{PORT}")

connected = True
while connected:
    msg = input("> ")

    client.send(msg.encode(FORMAT))

    if msg == DISCONNECT_MSG:
        connected = False
    else:
        msg = client.recv(SIZE).decode(FORMAT)
        print(f"[SERVER] {msg}")
    


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source