Close listening socket in python thread

后端 未结 5 947
一生所求
一生所求 2021-01-04 10:07

I have a problem trying to learn about sockets for network communication. I have made a simple thread that listens for connections and creates processes for connecting clien

5条回答
  •  独厮守ぢ
    2021-01-04 10:50

    The best way to do this is to have a single listening thread that has nothing to do with your connection threads and give it a reasonable length timeout. On timeout, check if this thread should shutdown and if not, loop again and go back to listening.

        def tcp_listen_handle(self, port=23, connects=5, timeout=2):
            """This is running in its own thread."""
            sock = socket.socket()
            sock.settimeout(timeout)
            sock.bind(('', port))
            sock.listen(connects)  # We accept more than one connection.
            while self.keep_running_the_listening_thread():
                connection = None
                addr = None
                try:
                    connection, addr = sock.accept()
                    print("Socket Connected: %s" % str(addr))
                    # makes a thread deals with that stuff. We only do listening.
                    self.handle_tcp_connection_in_another_thread(connection, addr)
                except socket.timeout:
                    pass
                except OSError:
                    # Some other error.
                    print("Socket was killed: %s" % str(addr))
                    if connection is not None:
                        connection.close()
            sock.close()
    

    The only thing this does is listen, timeout, checks if it should die during the timeout, and goes back to listening. The general rule of thumb is that threads should check whether they should die and try to do that themselves as fast as they can. And if you don't want to take the 2 second hit for timeout wait before the thread unblocks and checks. You can connect to it yourself.

提交回复
热议问题