[Tutor] Threading and Sockets

Wayne Werner waynejwerner at gmail.com
Mon Nov 15 16:44:51 CET 2010


Well, I solved the issue myself

I changed the server class to the following:

class Server(threading.Thread):
    def __init__(self, port=1500, max_connections=5):
        ''' Setup the server elements. '''

        threading.Thread.__init__(self)
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind(('localhost', 1500))
        self.server.listen(5)
        self.server.settimeout(5)
        self.keeprunning = True

    def run(self):
        global CONNCOUNT
        while self.keeprunning:#CONNCOUNT > 1:
            try:
                connection = self.server.accept()
                ClientThread(connection, self).start()
            except socket.timeout:
                # Just keep rolling
                pass
        self.stop()

    def stop(self):
        ''' Stop the server. '''

        print("Stopping server... maybe...")
        self.keeprunning = False
        # Close the socket connection
        self.server.close()
        print("Server stopped.")


With the timeout it will stop accepting a connection every 5 seconds, and
then try again for another 5 seconds.

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101115/2f34f1ee/attachment.html>


More information about the Tutor mailing list