How to stop a listening socket.accept()?

Dave Brueck dave at pythonapocrypha.com
Sat Mar 13 00:14:15 EST 2004


kvdvm wrote:
> It seems that the accept() method acts as stubborn as a mule to get a
> connection request even if I close it in another thread.
>
> Any idea will be deeply appreciated.

You can either make it non-blocking and use select in a loop, or you can have a
global flag indicate when it's time to shutdown, and open a dummy connection to
it, e.g. (untested):

class GV:
  quit = 0
  listenAddr = ('127.0.0.1', 2000)

def Listen(listenSock, handler):
  while 1:
    newSock, sockFrom = listenSock.accept()
    if GV.quit:
      newSock.close()
      break
    handler(newSock, sockFrom)

def StopListening():
  GV.quit = 1
  socket(AF_INET,SOCK_STREAM).connect(listenAddr)

-Dave





More information about the Python-list mailing list