
import time
from   twisted.internet import reactor, protocol


# a client protocol

errors = 0
connections = 100
count = 0
startTime = 0

def shouldFinish(error = 0):
     global errors
     global count
     global startTime

     count += 1

     if error:
        errors += 1

     if count >= connections:
        reactor.stop() 
        print connections, errors, time.time() - startTime


class EchoClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""
    
    def connectionMade(self):
        self.transport.write("hello, world!")
    
    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        print "Server said:", data
        self.transport.loseConnection()
    
    def connectionLost(self, reason):
        pass
        #print "connection lost"


class EchoFactory(protocol.ClientFactory):
    protocol = EchoClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        shouldFinish(1)
    
    def clientConnectionLost(self, connector, reason):
        #print "Connection lost - goodbye!"
        shouldFinish()


# this connects the protocol to a server runing on port 8000
def main():
    global startTime
    startTime = time.time()
    f = EchoFactory()
    for i in range(0,connections):
        reactor.connectTCP("localhost", 8001, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()
