I have a problem trying to find out about sockets for network communications. I made a simple thread that listens for connections and creates processes for connecting clients. My problem is that I cannot get the thread to connect properly, as I have not found a way to cancel socket.accept () - call when I want to exit the program.
My code is as follows:
class ServerThread( threading.Thread ): def __init__(self, queue, host, port): threading.Thread.__init__(self) self.queue = queue self.running = True self.hostname = host self.port = port def run(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.hostname, self.port)) self.socket.listen(1) while self.running: try: conn, address = self.socket.accept() process = Process(target=server_slave, args=(conn, address, self.queue)) process.daemon = True process.start() except socket.timeout: pass def stop(self): self.running = False self.socket.close()
I managed to close the program by setting self.setDaemon(True) and just exit the main program, passing everything to a large garbage collector, but this seems like a bad solution. I also tried setting a timeout for the socket, but this results in a [Errno 35] Resource temporarily unavailable (regardless of the actual timeout, even when I set it in years ...).
What am I doing wrong? Did I develop a thread at a dead end or miss something about accepting connections?
source share