Exemplo n.º 1
0
        await pool.spawn(proxy_one_way, b, a)


async def main(delay: int, a: tuple, b: tuple):
    """
    Sets up the proxy
    """

    start = giambio.clock()
    print(
        f"Starting two-way proxy from {a[0]}:{a[1]} to {b[0]}:{b[1]}, lasting for {delay} seconds"
    )
    async with giambio.skip_after(delay) as p:
        sock_a = giambio.socket.socket()
        sock_b = giambio.socket.socket()
        await sock_a.connect(a)
        await sock_b.connect(b)
        async with sock_a, sock_b:
            await proxy_two_way(sock_a, sock_b)
    print(f"Proxy has exited after {giambio.clock() - start:.2f} seconds")


try:
    giambio.run(main,
                60, ("localhost", 12345), ("localhost", 54321),
                debugger=())
except (Exception, KeyboardInterrupt) as error:  # Exceptions propagate!
    if isinstance(error, KeyboardInterrupt):
        print("Ctrl+C detected, exiting")
    else:
        print(f"Exiting due to a {type(error).__name__}: {error}")
Exemplo n.º 2
0
        await sock.send_all(
            b"Welcome to the server pal, feel free to send me something!\n")
        while True:
            await sock.send_all(b"-> ")
            data = await sock.receive(1024)
            if not data:
                break
            elif data == b"exit\n":
                await sock.send_all(b"I'm dead dude\n")
                raise TypeError("Oh, no, I'm gonna die!")
            logging.info(f"Got: {data!r} from {address}")
            await sock.send_all(b"Got: " + data)
            logging.info(f"Echoed back {data!r} to {address}")
    logging.info(f"Connection from {address} closed")


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 1501
    logging.basicConfig(
        level=20,
        format="[%(levelname)s] %(asctime)s %(message)s",
        datefmt="%d/%m/%Y %p",
    )
    try:
        giambio.run(serve, ("localhost", port))
    except (Exception, KeyboardInterrupt) as error:  # Exceptions propagate!
        if isinstance(error, KeyboardInterrupt):
            logging.info("Ctrl+C detected, exiting")
        else:
            logging.error(f"Exiting due to a {type(error).__name__}: {error}")
Exemplo n.º 3
0
import giambio
from debugger import Debugger


async def child(name: int):
    print(f"[child {name}] Child spawned!! Sleeping for {name} seconds")
    await giambio.sleep(name)
    print(f"[child {name}] Had a nice nap!")


async def main():
    start = giambio.clock()
    async with giambio.skip_after(10) as pool:
        await pool.spawn(child, 7)  # This will complete
        await giambio.sleep(2)  # This will make the code below wait 2 seconds
        await pool.spawn(child, 15)  # This will not complete
        await giambio.sleep(50)  # Neither will this
        await child(20)  # Nor this
    if pool.timed_out:
        print("[main] One or more children have timed out!")
    print(
        f"[main] Children execution complete in {giambio.clock() - start:.2f} seconds"
    )


if __name__ == "__main__":
    giambio.run(main, debugger=())
Exemplo n.º 4
0
async def task(c: giambio.MemoryChannel, name: str):
    while True:
        if await c.pending():
            print(f"[{name}] Received {await c.read()!r}")
        else:
            data = "".join(
                random.choice(string.ascii_letters) for _ in range(8))
            print(f"[{name}] Sending {data!r}")
            await c.write(data)
        await giambio.sleep(1)


async def main(channel: giambio.MemoryChannel, delay: int):
    print(f"[main] Spawning workers, exiting in {delay} seconds")
    async with giambio.skip_after(delay) as pool:
        await pool.spawn(task, channel, "one")
        await pool.spawn(task, channel, "two")
        await pool.spawn(task, channel, "three")
    await channel.close()
    print(f"[main] Operation complete, channel closed")
    if await channel.pending():
        print(
            f"[main] Channel has {len(channel.buffer)} leftover packet{'s' if len(channel.buffer) > 1 else ''} of data, clearing it"
        )
        while await channel.pending():
            print(f"[main] Cleared {await channel.read()!r}")


channel = giambio.MemoryChannel()
giambio.run(main, channel, 6, debugger=())
Exemplo n.º 5
0
    """

    queue = giambio.Queue()
    async with giambio.create_pool() as pool:
        async with giambio.socket.socket() as sock:
            await sock.connect(host)
            await pool.spawn(sender, sock, queue)
            await pool.spawn(receiver, sock, queue)
            while True:
                op, data = await queue.get()
                if op == 0:
                    print(f"Sent.")
                else:
                    print(f"Received: {data}")


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 1501
    logging.basicConfig(
        level=20,
        format="[%(levelname)s] %(asctime)s %(message)s",
        datefmt="%d/%m/%Y %p",
    )
    try:
        giambio.run(main, ("localhost", port))
    except (Exception, KeyboardInterrupt) as error:  # Exceptions propagate!
        if isinstance(error, KeyboardInterrupt):
            logging.info("Ctrl+C detected, exiting")
        else:
            logging.error(f"Exiting due to a {type(error).__name__}: {error}")
Exemplo n.º 6
0
    print("[child] Child is alive! Going to wait until notified")
    start_total = giambio.clock()
    data = await ev.wait()
    end_pause = giambio.clock() - start_total
    print(f"[child] Parent set the event with value {data}, exiting in {pause} seconds")
    start_sleep = giambio.clock()
    await giambio.sleep(pause)
    end_sleep = giambio.clock() - start_sleep
    end_total = giambio.clock() - start_total
    print(
        f"[child] Done! Slept for {end_total:.2f} seconds total ({end_pause:.2f} waiting, {end_sleep:.2f} sleeping), nice nap!"
    )


async def parent(pause: int = 1):
    async with giambio.create_pool() as pool:
        event = giambio.Event()
        print("[parent] Spawning child task")
        await pool.spawn(child, event, pause + 2)
        start = giambio.clock()
        print(f"[parent] Sleeping {pause} second(s) before setting the event")
        await giambio.sleep(pause)
        await event.trigger(True)
        print("[parent] Event set, awaiting child completion")
    end = giambio.clock() - start
    print(f"[parent] Child exited in {end:.2f} seconds")


if __name__ == "__main__":
    giambio.run(parent, 3, debugger=())
Exemplo n.º 7
0
                print(f"Received {len(data)} bytes")
                if data:
                    buffer += data
                else:
                    print("Received empty stream, closing connection")
                    break
    print(f"Request has{' not' if not p.timed_out else ''} timed out!")
    if buffer:
        data = buffer.decode().split("\r\n")
        print(f"HTTP Response below {'(might be incomplete)' if p.timed_out else ''}")
        _print(f"Response: {data[0]}")
        _print("Headers:")
        content = False
        for i, element in enumerate(data):
            if i == 0:
                continue
            else:
                if not element.strip() and not content:
                    # This only works because google sends a newline
                    # before the content
                    sys.stdout.write("\nContent:")
                    content = True
                if not content:
                    _print(f"\t{element}")
                else:
                    for line in element.split("\n"):
                        _print(f"\t{line}")


giambio.run(test, "google.com", 443, 256, debugger=())
Exemplo n.º 8
0
        await q.put(i)
        print(f"Produced {i}")
    await q.put(None)
    print("Producer done")


async def consumer(q: giambio.Queue):
    while True:
        # Hangs until there is
        # something on the queue
        item = await q.get()
        if item is None:
            print("Consumer done")
            break
        print(f"Consumed {item}")
        # Simulates some work so the
        # producer waits before putting
        # the next value
        await giambio.sleep(1)


async def main(q: giambio.Queue, n: int):
    async with giambio.create_pool() as pool:
        await pool.spawn(producer, q, n)
        await pool.spawn(consumer, q)
    print("Bye!")


queue = giambio.Queue(1)  # Queue has size limit of 1
giambio.run(main, queue, 5, debugger=())
Exemplo n.º 9
0
import giambio


async def child():
    print("[child] Child spawned!! Sleeping for 4 seconds")
    await giambio.sleep(4)
    print("[child] Had a nice nap!")


async def child1():
    print("[child 1] Child spawned!! Sleeping for 2 seconds")
    await giambio.sleep(2)
    print("[child 1] Had a nice nap!")


async def main():
    start = giambio.clock()
    async with giambio.create_pool() as pool:
        await pool.spawn(child)
        await pool.spawn(child1)
        print("[main] Children spawned, awaiting completion")
    print(
        f"[main] Children execution complete in {giambio.clock() - start:.2f} seconds"
    )


if __name__ == "__main__":
    giambio.run(main)