[Twisted-Python] how to best limit a given protocol to one instance (socket connection)?

Jp Calderone exarkun at intarweb.us
Tue Dec 2 21:10:59 EST 2003

On Tue, Dec 02, 2003 at 05:58:35PM -0800, John Benson wrote:
> Hi, I'd like to ensure that only one client can get into my instance of
> Protocol. I'm thinking of setting an "instances" attribute on the Factory
> and losing the connection if it has already been incremented to 1, but I'm
> wondering if there is something more forceful that says "server rejected
> connection" that might be a twisted Factory or Protocol configuration
> option.

  You could turn off the listening port after the first connection.

    class Factory(ServerFactory):
	port = None
        def buildProtocol(self, addr):
            if self.port is not None:
                self.port = None
                # This is necessary in case multiple
                # connections are made before the call
                # to stopListening above is made.
                return None

    f = Factory()
    f.port = reactor.listenTCP(port, f)

  This will refuse *almost* all connections after the first.  It is still
possible that two or more might arrive at nearly the same time and both be
accept()'d, but after buildProtocol runs for the first time, no further
connections will be able to be made, as the listening socket will not longer
be listening.

  I'm not sure if there's a way to eliminate the possibility of multiple
connections being made close together.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://twistedmatrix.com/pipermail/twisted-python/attachments/20031202/2551e868/attachment.pgp 

More information about the Twisted-Python mailing list