title: How to limit the number of connections to a socket and trigger timeout on client (Python)
body: <p>How can I set a limit on the number of connections that a server socket can accept at once? I want to be able to set a max number of connections, and then once that limit is reached, any further attempts from clients to connect will result in a timeout. So far, I have tried something like this for the server:</p>
  
  <pre><code>sock = socket.socket()
  sock.setblocking(0)
  sock.bind(address)
  sock.listen(0)
  
  connections = []
  
  while True:
      readable, writable, exceptional = select.select([sock], [], [])
  
      if readable and len(connections) &lt; MAX_CONNECTIONS:
          connection, client_address = s.accept()
          connections.append(connection)
          # Process connection asynchronously
  </code></pre>
  
  <p>and for the client:</p>
  
  <pre><code>try:
      sock = socket.create_connection(self.address, timeout=TIMEOUT)
      sock.settimeout(None)
      print "Established connection."
  except socket.error as err:
      print &gt;&gt; sys.stderr, "Socket connection error: " + str(err)
      sys.exit(1)
  
  # If connection successful, do stuff
  </code></pre>
  
  <p>Because of the structure of the rest of the program, I have chosen to use a non-blocking socket on the server and I do not wish to change this. Right now, the clients are able to connect to the server, even after the limit is reached and the server stops accepting them. How do I solve this? Thanks.</p>