I have a small python console that works over UDP. The problem I'm having is that if I abruptly disconnect from the client, the connection stays open in netstat (because it's UDP).

I have tried implementing a threading.Timer in the server that asks if the connection is active, and if the client does not respond within that time, the connection closes from the server-side.

This is what I tried

def check_conn(sock: socket.socket):
    # sock.settimeout()
    sock.send(b"\nAwake?")
    try:
        ack = sock.recv(1024)
        ack = ack.decode("UTF-8")
        if ack.strip() == "Yea":
            pass
        else:
            sock.close()
    except:
        sock.close()


so = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
so.connect((host, port))
t = threading.Timer(10.0, check_conn, [so])
t.start()
data = so.recv(1024)
#rest of the main program

The problem I'm having is that when it asks for the password, two so.recv(1024) are open, and it does not know how to handle them (that's my guess).

0 Answers