| 1 | import sys |
|---|
| 2 | |
|---|
| 3 | from twisted.internet.epollreactor import install |
|---|
| 4 | install() |
|---|
| 5 | |
|---|
| 6 | from twisted.python import log |
|---|
| 7 | from twisted.internet import reactor |
|---|
| 8 | from twisted.internet.protocol import ClientCreator, Protocol |
|---|
| 9 | from twisted.internet.defer import Deferred, gatherResults |
|---|
| 10 | from twisted.internet.task import coiterate |
|---|
| 11 | |
|---|
| 12 | class Client(Protocol): |
|---|
| 13 | counter = 0 |
|---|
| 14 | outstandingConnects = 0 |
|---|
| 15 | mostEver = 0 |
|---|
| 16 | |
|---|
| 17 | def __init__(self): |
|---|
| 18 | self.lost = Deferred() |
|---|
| 19 | |
|---|
| 20 | def connectionMade(self): |
|---|
| 21 | self.lost.callback(None) |
|---|
| 22 | if Client.outstandingConnects > Client.mostEver: |
|---|
| 23 | print 'Most ever outstanding connects:', Client.outstandingConnects |
|---|
| 24 | Client.mostEver = Client.outstandingConnects |
|---|
| 25 | |
|---|
| 26 | Client.outstandingConnects -= 1 |
|---|
| 27 | Client.counter += 1 |
|---|
| 28 | if Client.counter % 1000 == 0: |
|---|
| 29 | print 'Connected', Client.counter, Client.outstandingConnects |
|---|
| 30 | |
|---|
| 31 | self.transport.write('GET / HTTP/1.1\r\n\r\n') |
|---|
| 32 | |
|---|
| 33 | |
|---|
| 34 | def main(host, port, total, concurrent): |
|---|
| 35 | cc = ClientCreator(reactor, Client) |
|---|
| 36 | def f(): |
|---|
| 37 | for n in xrange(total): |
|---|
| 38 | Client.outstandingConnects += 1 |
|---|
| 39 | ip = '127.%d' % (n % 256,) |
|---|
| 40 | d = cc.connectTCP(host, port, bindAddress=(ip, 0)) |
|---|
| 41 | d.addCallback(lambda proto: proto.lost) |
|---|
| 42 | yield d |
|---|
| 43 | g = f() |
|---|
| 44 | d = gatherResults([coiterate(g) for n in range(concurrent)]) |
|---|
| 45 | d.addErrback(log.err) |
|---|
| 46 | d.addCallback(lambda ign: reactor.stop()) |
|---|
| 47 | reactor.run() |
|---|
| 48 | |
|---|
| 49 | log.startLogging(sys.stdout) |
|---|
| 50 | main('127.0.0.1', 2000, 100000, 100) |
|---|