# Py - TCP/IP http server of  file 4_index.html
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-10-30  initial release

import  socket

# ============================ local =============================

def getHtml(fn='4_index.html'):
    with open(fn) as f:
        return f.read()
    
# ============================ main ==============================

HOST	= '0.0.0.0'			# all interfaces
PORT	= 5000           	# listening port

def main():
    try:
        print('server running ...')
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as ss:	# IPv4 & stream
            ss.setsockopt(socket.SOL_SOCKET ,socket.SO_REUSEADDR, 1)
            ss.bind((HOST, PORT))										# bind unbound address									
            ss.listen(0)												# enable server, allowed unaccepted connections
            while True:
                cs, addr = ss.accept()										# client socket object
                with cs:
                    print('Connected by', addr)
                    data = cs.recv(1024)
                    if data:
                        print('Rx:', data, '\n')
                        tx_data = f'HTTP/1.0 200 OK\n\n{getHtml()}\n'
                        cs.sendall(tx_data.encode())
    except:
        print('server terminated')
        
        
main()

# ============================ end ===============================
