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

2020-06-03 01:30发布

问题:

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. Plzzzz somebody help.

回答1:

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).