I want to implement event loop using asyncio and socket to handle multiple requests (#ZU2)

My code so far handles the 1st client nicely but cannot handle the second one

Here are my logs:

[stage-4] client-1: $ redis-cli PING
[stage-4] client-1: Sent bytes: "*1\r\n$4\r\nPING\r\n"
[your_program] [+] Client 1 - ('', 56376) connected
[your_program] Received request b'*1\r\n$4\r\nPING\r\n' <socket.socket fd=7, family=2, type=1, proto=0, laddr=('', 6379), raddr=('', 56376)>
[stage-4] client-1: Received bytes: "+PONG\r\n"
[stage-4] client-1: Received RESP value: "PONG"
[stage-4] Received "PONG"
[stage-4] client-2: $ redis-cli PING
[stage-4] client-2: Sent bytes: "*1\r\n$4\r\nPING\r\n"
[stage-4] Received: "" (no content received)
[stage-4]            ^ error
[stage-4] Error: Expected start of a new RESP2 value (either +, -, :, $ or *)
[stage-4] Test failed
[stage-4] Terminating program
[stage-4] Program terminated successfully

And here’s a snippet of my code:

async def server_start(server_socket):
    print(f"[+] SERVER LISTENING on f{SERVER}:f{PORT}")
    loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()  # start event loop
    while True:
        client_socket, client_address = await loop.sock_accept(server_socket)
        await loop.create_task(handle_client(client_socket, client_address))

async def handle_client(client_socket, client_address):
    global connections
    connections += 1
    conn_no = connections
    print(f"[+] Client {conn_no} - {client_address} connected")
    loop = asyncio.get_event_loop()
    while req := await loop.sock_recv(client_socket, 1024):
        print("Received request", req, client_socket)
        await loop.sock_sendall(client_socket, PONG.encode())

def server_init():
    # SERVER = socket.gethostbyname(socket.gethostname())


    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    return server_socket

Your issue is probably the await on create task. You don’t really need to wait for that.

^ Yep, I think that’s the answer! Would explain why your first client is served, but the second client isn’t accepted (since the await goes on forever as long as the first client is being served)

Going to close this out, please let us know if you still need help!

yes @lakshya24 your advice was spot on the only reason I did not do it first because pycharm kept drawing a yellow line. Thanks all of you for the help. I am closing the thread

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.

Note: I’ve updated the title of this post to include the stage ID (#ZU2). You can learn about the stages rename here: Upcoming change: Stages overhaul.