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
Active
Viewed 1.9k times
16
Neuron - Freedom for Ukraine
- 4,303
- 4
- 29
- 51
cybernerd
- 173
- 1
- 1
- 6
-
3You should check out the `socket.setblocking` function and the [`select`](http://docs.python.org/library/select.html) module. – Some programmer dude Apr 10 '12 at 14:05
1 Answers
16
You have several options here:
- Close the listening socket from another thread - the
accept()will raise an exception if it fails. - Open a local connection to the listening socket - that makes the
accept()return by design. - 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.
- Use a non-blocking alternative to
accept(), (async likeAcceptEx()and overlapped IO on Windows).
Niklas B.
- 89,411
- 17
- 190
- 222
Martin James
- 23,993
- 3
- 34
- 58
-
1@NiklasB. - thanks. I don't have any Python, but the OP question is more a general TCP server issue and the same set of 'tricks' are needed in all languages. – Martin James Apr 10 '12 at 14:49
-
1Can you give an example because as stated earlier i am a newbie....i am actually writing a server in pygtk. My problem is that the window hangs because of the socket.accept() call. – cybernerd Apr 11 '12 at 08:47
-
1On OSX 10.10 with Python 2.7.6, (1) is unreliable. However, using a `quit_now` style flag in the accept loop and then connecting (2) to trigger a return from accept() works fine. – Harvey Jan 19 '15 at 17:19
-
2Option #2 seems to be most appropriate for several of my applications. – Johnny Utahh Apr 17 '15 at 00:23
-
2Could you show examples of these? You have no idea how useful they'd be. – byxor Dec 01 '16 at 17:11