# zie ProgrammeursleerlingExtra.py
# Aanvulling 49
# onderdeel Server extern met client 2

import network
import socket

print( 'server2.py for MicroPython on ESP32' )

ap = network.WLAN( network.WLAN.IF_AP ) # access point
ap.config( ssid='ESP-AP4' )             # naam
ap.config( max_clients=10 )
ap.active( True )

print( ap.config( 'mac' ) )
print( ap.ipconfig( 'addr4' ) )
# print( ap.ifconfig( 'addr4' ) )

host = ''
port = 5001
srvaddr = host, port

def server():
    # in MicroPython 1.26.1
    # AttributeError: 'socket' object has no attribute '__exit__'
    # with socket.socket() as srv:

    srv = socket.socket()
    try:
        srv.bind( srvaddr )
        srv.listen()
        print( 'server listen', srvaddr )
        clnt, claddr = srv.accept()
        try:
            print( 'server connect', claddr )
            while True:
                data = clnt.recv( 1024 )
                # print( 'data', data )

                # if data == b'': 
                if data == b'stop':
                    print( 'server client done' )
                    break
                data = b'echo:' + data
                clnt.sendall( data )
                print( 'server', data )
        finally:
            clnt.close()
    finally:
        srv.close()
    print( 'end server' )

server()
