import asyncio
import threading


HOST = 'localhost'
PORT = 9000
CLIENTS = []

async def echo_server(reader, writer):
    while True:
        data = await reader.read(100)  # Max number of bytes to read
        if not data:
            break
        writer.write(data)
        await writer.drain()  # Flow control, see later
    writer.close()

async def startServer(host, port):
    server = await asyncio.start_server(echo_server, host, port)
    print(f"Server Started at {HOST} on {PORT}")
    await server.serve_forever()
    
def setLoopEventForServerStart():
    startServerLoop = asyncio.new_event_loop()
    asyncio.set_event_loop(startServerLoop)
    asyncio.run(startServer(HOST, PORT))

async def createClient():
    client = await asyncio.open_connection(HOST, PORT)
    if client:
        CLIENTS.append(client)
        print(f"Client appended {client}")
        return client



async def sendMessageToServer(socket, message="hello World"):
    reader, writer = socket
    writer.write(message)
    writer.drain()


# startServerThread = threading.Thread(target=setLoopEventForServerStart)
# startServerThread.start()

if __name__ == "__main__":
    startServer(HOST, PORT)
    asyncio.run(createClient())