1
votes

I have a server socket that listens for incoming connections and creates new sockets for each client. I have a while loop to keep the server responsible (being able to close it using a button when there are no connections incoming) and for that i use .select to check if there are any connections. The problem I'm having is that .select is blocking for some reason. It waits until there is a connection instead of checking for a connection and then moving on.

    def serverstart(self):
      self.buttonswitch("1")
      self.host = self.intip
      self.port = 5000
      s = socket.socket(socket.AF_INET6)
      s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      s.setblocking(0)
      s.bind((self.host, self.port))

      inputs = [ s ]

      s.listen(5)
      self.serverstatus = "1"
      while s:
            inputready, outputready, exceptready = select.select(inputs, [], [] )
            if inputready == inputs and self.serverstatus == "1":
                    print inputready
                    c, addr = s.accept()
                    ct = threading.Thread(target=self.client_thread, args=[c, addr])
                    ct.start()
            if self.serverstatus == "0":
                    break
      s.close()
      print "Closing socket"
      self.buttonswitch("0")

Edit:

Added timeout for a working non-blocking select solution

            inputready, outputready, exceptready = select.select(inputs, [], [], 0.1 )
1
"close it using a button" ... so this is part of a GUI? Does the GUI have its own method for handling sockets?tdelaney

1 Answers

5
votes

The fourth parameter to select is a timeout. According to the docs:

The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready.

If you're wanting to avoid the default behavior you should modify your call to include the optional parameter. select(inputs, [], [], 1), for example.

Python Select Docs