How to stop a python socket.accept() call?

Question:

I am a newbie in python sockets and am really troubled by the stubbornness of the socket.accept() method. I really need a way of ending a socket.accept() method or any other alternative to socket.accept() which runs one time only.

Asked By: cybernerd

||

Answers:

You have several options here:

  1. Close the listening socket from another thread – the accept() will raise an exception if it fails.
  2. Open a local connection to the listening socket – that makes the accept() return by design.
  3. Use an accept mechanism that can block on more than one synchronization object so that the wait can be signaled to return without a connection.
  4. Use a non-blocking alternative to accept(), (async like AcceptEx() and overlapped IO on Windows).
Answered By: Martin James

Iam posting this because accepted answer is incomplete, On Unix the circumstances are a little bit more complicated.

crossplatform code:

class KeyServer:

    HOST = "127.0.0.1"
    PORT = int(os.getenv("PL_CREDENTIAL_SERVER_PORT", "55955"))

    def __init__(self, args):
        self.args = args
        self.script_checker = ScriptChecker(args)
        self.sock = None

    def listen(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((KeyServer.HOST, KeyServer.PORT))
        self.sock.listen(20)

        while True:
            try:
                readable, _, _ = select.select([self.sock], [], [], 1.0)
                if self.sock in readable:
                    conn, addr = self.sock.accept()
                    conn.settimeout(0.5)
                    print(f"Connected by {addr}", flush=True)
                    connstream = conn
                    ServerThread(connstream, self).start()
            except Exception:
                traceback.print_exc()
                break

        try:
            self.sock.close()
        except Exception:
            pass

Used class Serverthread can now close() the socket. Without using select, the accept method will remain in an unusable state. Because it will wait for the sock to be readable and exactly this must be clarified before.

Answered By: Nikolai Ehrhardt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.