Images not displaying in multi-threaded server?

I manage to make a code of a multi-threaded server that successfully send the HTML to the client, but for some reason the webpage doesn´t display images. Can someone please check my code for errors?

# import socket and threading libraries
from socket import *
import threading

# function to handle client thread
def handle_client(t_connection, t_address):
    # print client acknowledgment and address
    print(f"new connection: {t_address} connected.\n")

    # infinite loop to maintain connection
    while True:
        try:
            # receive message from browser
            message = t_connection.recv(1024).decode("utf-8")

            # handle message from browser
            filename = message.split()[1]

            # open requested file
            file = open(filename[1:])

            # assign requested file data to output variable
            output_data = file.read()

            # send OK HTTP response
            t_connection.send("""HTTP/1.0 200 OK """.encode("utf-8"))

            # send requested file
            t_connection.send(output_data.encode("utf-8"))

            # close connection
            t_connection.close()

        # handle errors
        except IOError:
            # send Page Not Found HTTP response
            t_connection.send("""HTTP/1.0 404 Page Not Found """.encode("utf-8"))

            # close connection
            t_connection.close()
            pass
        # break from infinite loop
        break


def main():
    # set IP address dynamically
    ip = "localhost"

    # define port number address
    port = 80

    # define address topple
    address = (ip, port)

    # print initial server status message
    print("starting server!")

    # Initializing connection socket
    server = socket(AF_INET, SOCK_STREAM)

    # assigning ip address and a port number to socket instance.
    server.bind(address)

    # start listening to incoming requests
    server.listen(1)

    # print server listening address
    print(f"listening on {ip}:{port}")

    # infinite loop to maintain server live
    while True:
        # accept client connection
        connection, address = server.accept()

        # initialize new thread for client
        thread = threading.Thread(target=handle_client, args=(connection, address))

        # start new thread for client
        thread.start()

        # print client count
        print(f"connected clients: {threading.activeCount() - 1}")


# start program
if __name__ == "__main__":
    main()

Sorry, for any error while posting my question. I’m new to the forum.

Something you can do to make the things look better is put all the Python code into a code block, like this:

```
{all the code you posted above goes here}
```

Just edit your first post.

Thanks for the advice. Already edited!

1 Like