Saturday, 18 February 2023

Python socket non-blocking recv() exception(s) and sendall() exception

I'm writing a simple TCP relay server, which is gonna be deployed both on a Windows and a Linux machine (same code base). Naturally there're gonna be two sockets to work with. I would like to know which exceptions exactly do get raised for the following cases:

  1. recv() returns when no data is available to read.
  2. sendall() cannot complete (dispose of the whole to-send data)
  • Do I have to check for both errnos (socket.EWOULDBLOCK and socket.EAGAIN) when expecting to return from a non-blocking sockets recv()?
  • Which errno (.args[0]) do I get when sendall() fails?

Here's my code so far:

try:
    socket1.setblocking(False)
    socket2.setblocking(False)

    while True:
        try:
            sock1_data = socket1.recv(1024)
            if sock1_data:
                socket2.sendall(sock1_data)
        except socket.error as e:
            if e.args[0] != socket.EAGAIN and e.args[0] != socket.EWOULDBLOCK:
                raise e

        try:
            sock2_data = socket2.recv(1024)
            if sock2_data:
                socket1.sendall(sock2_data)
        except socket.error as e:
            if e.args[0] != socket.EAGAIN and e.args[0] != socket.EWOULDBLOCK:
                raise e
except:
    pass
finally:
    if socket2:
        socket2.close()
    if socket1:
        socket1.close()

My main concern is: What socket.error.errno do I get when sendall() fails?

Lest the socket.error.errno I get from a failing sendall() is EAGAIN or EWOULDBLOCK, in which case it'd be troubling!!

Also, do I have to check for both EAGAIN and EWOULDBLOCK when handling a non-blocking recv()?



from Python socket non-blocking recv() exception(s) and sendall() exception

No comments:

Post a Comment