import selectors
import socket
import json

sel = selectors.DefaultSelector()

clients = {}  # Dictonary, um Clients zu speichern

def accept_wrapper(sock):
    conn, addr = sock.accept()
    print(f"Verbunden mit {addr}")
    conn.setblocking(False)
    data = types.SimpleNamespace(addr=addr, inb=b"", outb=b"")
    events = selectors.EVENT_READ | selectors.EVENT_WRITE
    sel.register(conn, events, data=data)

def service_connection(key, mask):
    sock = key.fileobj
    data = key.data

    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(1024)
        if recv_data:
            data.outb += recv_data
            try:
                received_json = json.loads(recv_data.decode())
                # Hier könnte man weitere Verarbeitungsschritte für die empfangenen Daten durchführen
            except json.JSONDecodeError:
                pass
        else:
            print("Verbindung geschlossen mit", data.addr)
            sel.unregister(sock)
            sock.close()
            del clients[data.addr]

    if mask & selectors.EVENT_WRITE:
        if data.outb:
            sent = sock.send(data.outb)
            data.outb = data.outb[sent:]

def start_server():
    host = '127.0.0.1'
    port_tcp = 65432
    port_udp = 65433

    server_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_tcp.bind((host, port_tcp))
    server_tcp.listen()
    server_tcp.setblocking(False)
    sel.register(server_tcp, selectors.EVENT_READ, data=None)

    server_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_udp.bind((host, port_udp))
    server_udp.setblocking(False)
    sel.register(server_udp, selectors.EVENT_READ, data=None)

    while True:
        events = sel.select(timeout=None)
        for key, mask in events:
            if key.data is None:
                accept_wrapper(key.fileobj)
            else:
                service_connection(key, mask)

if __name__ == "__main__":
    start_server()
