import asyncio
import json
import ssl

# async def tcp_server(reader, writer):
#     data = await reader.read(100)
#     message = data.decode()
#     addr = writer.get_extra_info('peername')
#     print("Received %r from %r" % (message, addr))
#
#     print("Send: %r" % message)
#     writer.write(data)
#     await writer.drain()
#
#     print("Close the client socket")
#     writer.close()

async def tcp_server(reader, writer):
    # data = await reader.read(-1)
    while True:
        data = await reader.readuntil(separator=b'\n')
        if not data:
            writer.close()
        message = data.decode()
        addr = writer.get_extra_info('peername')
        # print("Received {} from {}".format(message.rstrip(), addr))
        print(message)

        # print("Send: {} to client...".format(message))
        # writer.write("Data written successfully to transport...")
        # await writer.drain()

print("Close the client socket")
    # writer.close()


#sc = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
#sc.load_cert_chain('selfsigned.cert', 'selfsigned.key')


loop = asyncio.get_event_loop()
coro = asyncio.start_server(tcp_server, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
