import socket
import threading

IP = '0.0.0.0'
PORT = 9998

def main():
    """The main function setup the socket our server listening on""" 
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Set the ip address and port the server will be listening on, and start listening
    server.bind((IP,PORT))
    server.listen(5)
    print(f'[Listening on {IP}:{PORT}]')

    # Keep looping until client connect
    while True:
        client , address = server.accept()
        print(f'[Accept Connection from {address[0]}:{address[1]}]')
        # Create a new thread that call the receive_data function to handle data from client
        client_handler = threading.Thread(target=receive_data,args=(client,))
        client_handler.start()

def receive_data(client_socket):
    """To handle the data received from the client

    Arguments:
    client_socket -- the client's socket
    """
    with client_socket as sock:
        request = sock.recv(1024)
        print(f'[Received] \r\n {request.decode("utf-8")}')
        # Send back acknowledge message to the client
        sock.send(b'ACK: Message Received')

if __name__ == '__main__':
    main()
