[Twisted-python] help about create a tcp connection pool using twisted

Phil Mayers p.mayers at imperial.ac.uk
Thu Jul 24 07:41:33 EDT 2008

陳毅泰 wrote:
>     Hi, if I want to make a tcp connection pool by twisted, how can I do 
> that?? I am confuse about what should I keep?? The procotol instance
>    or something else, thanks a lot...

Yes, you'd keep a number of protocol instances. So for example:

from twisted.internet import protcol, reactor

class MyPool:
   max_connections = 16

   def __init__(self, host, port, prot_class, *p, **kw):
     self.host = host
     self.port = post
     self.factory = protocol.ClientCreator(reactor, prot_class, *p, **kw)
     self.connections = {}
     self.in_use = {}

   def doSomething(self, *p, **kw):
     # find a free protocol
     for id, instance in self.connections.items():
       if id in self.in_use:
       return self.got_conn(instance, id, *p **kw)

     # no free ones, create a new one
     for id in range(self.max_connections):
       if id in self.connections:

       d = self.factory.connectTCP(self.host, self.port)
       d.addCallback(self.got_conn, id, *p, **kw)
       return d

     raise Exception('pool full')

   def got_conn(self, proto, id, *p, **kw):
     self.connections[id] = proto
     self.in_use[id] = True
     d = proto.doSomething(*p, **kw)
     d.addBoth(self.done, id)

   def done(self, r, id):
     del self.in_use[id]
     return r

More information about the Twisted-Python mailing list