1# Test uasyncio stream readexactly() method using TCP server/client
2
3try:
4    import uasyncio as asyncio
5except ImportError:
6    try:
7        import asyncio
8    except ImportError:
9        print("SKIP")
10        raise SystemExit
11
12PORT = 8000
13
14
15async def handle_connection(reader, writer):
16    writer.write(b"a")
17    await writer.drain()
18
19    # Split the first 2 bytes up so the client must wait for the second one
20    await asyncio.sleep(0.1)
21
22    writer.write(b"b")
23    await writer.drain()
24
25    writer.write(b"c")
26    await writer.drain()
27
28    writer.write(b"d")
29    await writer.drain()
30
31    print("close")
32    writer.close()
33    await writer.wait_closed()
34
35    print("done")
36    ev.set()
37
38
39async def tcp_server():
40    global ev
41    ev = asyncio.Event()
42    server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT)
43    print("server running")
44    multitest.next()
45    async with server:
46        await asyncio.wait_for(ev.wait(), 10)
47
48
49async def tcp_client():
50    reader, writer = await asyncio.open_connection(IP, PORT)
51    print(await reader.readexactly(2))
52    print(await reader.readexactly(0))
53    print(await reader.readexactly(1))
54    try:
55        print(await reader.readexactly(2))
56    except EOFError as er:
57        print("EOFError")
58    print(await reader.readexactly(0))
59
60
61def instance0():
62    multitest.globals(IP=multitest.get_network_ip())
63    asyncio.run(tcp_server())
64
65
66def instance1():
67    multitest.next()
68    asyncio.run(tcp_client())
69