[Twisted-Python] How to accept connections faster

Sinang, Danny D.Sinang at spitech.com
Wed Mar 16 20:25:58 EST 2005

Hi Mike,

Thanks for the tip. My code is indeed running faster now.

However, the reason for the loop was to somehow simulate late responses
from a remote database server.

I'm guessing I should put the database query code in the closeInABit
method you mentioned like this :

def closeInABit ():
        mydb = MySQLdb.Connect(db='mydatabase', host="",
user="myuser", passwd="mypassword")
        cursor = mydb.cursor()

        retval = ''
        cursor = mydb.cursor()
        cursor.execute("SELECT * FROM Employees WHERE empnum = 'ABCD'")
	  retval = cursor.fetchone()
	  if retval == SomeValue:
		self.transport.write("Login Ok")
		self.transport.write("Login not Ok")

Is this ok ? Or should there be some special Asycn coding technique I
must also learn ?



Mike C. Fletcher wrote :

Danny, Twisted is an asynchronous system.  You *cannot* use that kind of
blocking delay tactic in Twisted without totally destroying Twisted's

>         for i in range(10000000):
>             pass
>         print "Looping done."
>         self.transport.loseConnection()
should have been something like:

    def closeInABit( ):
    reactor.callLater( 2, closeInABit ) # call after 2 seconds

You'll want to read up on asynchronous programming (e.g. on the Twisted
web site) to get a feel for how this model of programming networked apps

Good luck,

Sinang, Danny wrote:

> Hello.
> I ran the (Twisted) server code below and it accepts a client socket 
> connection every 1.3 seconds. The equivalent Synchronous socket code 
> accepts one every 2 seconds.
> Can anyone here suggest any code improvements for my Twisted server to

> accept connections faster ?
> I've include the Synchronous socket server code and the client 
> generator code below as well.

  Mike C. Fletcher
  Designer, VR Plumber, Coder
                              PyCon is coming...

More information about the Twisted-Python mailing list