Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sockets

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.

like image 354
cybernerd Avatar asked Apr 10 '12 13:04

cybernerd


People also ask

How do you stop a Python socket?

To close the connection, break the while loop. Garbage collection will remove the thread or process but join will ensure none get left behind. Persistent sockets close when the user closes them or they timeout. Non-persistent, like static webpages will close after they've sent the information.

How do you accept a socket in Python?

The accept() method is called on a TCP based server socket. When connect() is called at the client side with the IP address and port number of the server, the connect request is received with the accept() call at the server side.

Do you need to close socket Python?

It is only ever necessary to shutdown a socket for writing if (1) you have forked the process and definitely want to send the FIN now, or (2) you are engaging in a mutual read-to-EOS protocol such that both peers close at the same time. Otherwise close() is sufficient. The Python documentation should be corrected.

What is the default timeout of a socket in Python?

A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.


1 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).
like image 160
Martin James Avatar answered Oct 22 '22 00:10

Martin James