how do I stop SocketServer()?

Uberman bhood2 at comcast.net
Wed Aug 27 14:13:47 EDT 2008


On Wed, 27 Aug 2008 18:44:46 +0200, "Diez B. Roggisch"
<deets at nospam.web.de> wrote:

>Alexandru  Mosoi wrote:
>
>> supposing that I have a server (an instance of SocketServer()) that
>> waits for a connection (ie is blocked in accept()) and in another
>> thread i want to stop the server, how do I do that?
>
>By setting a timeout on the socket using socket.settimeout, and then
>periodically check for an abortion condition in the server thread before
>re-accepting connections.

You can also poll for activity by using the select() call.  For
example:

  ...
  local_host = ''     # Symbolic name meaning the local host

  server_port = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  server_port.bind((local_host, local_port))
  server_port.listen(1)

  readsocks = []
  readsocks.append(sync_port)

  # 'halt' would be your stop condition, set elsewhere
  while halt == False:
    readables, writeables, exceptions = select(readsocks, [], [], 1)

    # does the socket has a connection pending?
    if server_port in readables:
      # process client connection
      client_conn, client_addr = server_port.accept()
      ...



More information about the Python-list mailing list