Created
December 20, 2009 04:40
-
-
Save mnot/260353 to your computer and use it in GitHub Desktop.
http_conn_timer.py: find out how long a HTTP server keeps connections open
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
http_conn_timer.py | |
by Mark Nottingham <mnot@pobox.com> | |
How long does a given HTTP server hold persistent connections open? | |
Requires Twisted <http://twistedmatrix.com/> | |
""" | |
import time | |
from twisted.internet import defer, protocol, reactor | |
from twisted.python import log | |
class ConnTimerProtocol(protocol.Protocol): | |
connect_time = None | |
def connectionMade(self): | |
self.transport.write("HEAD / HTTP/1.0\r\n") | |
self.transport.write("Host: %s:%s\r\n" % (self.factory.host, self.factory.port)) | |
self.transport.write("Connection: keep-alive\r\n") | |
self.transport.write("\r\n") | |
def connectionLost(self, reason): | |
if self.connect_time: | |
time_connected = time.time() - self.connect_time | |
print "Connected: %2.2f" % time_connected | |
reactor.stop() | |
def dataReceived(self, data): | |
self.connect_time = time.time() | |
lines = data.split("\n") | |
for line in lines: | |
if ":" not in line: continue | |
name, value = line.split(":", 1) | |
if name.strip().lower() in ['server', 'keep-alive', 'via']: | |
print line.strip() | |
class ConnTimerFactory(protocol.ClientFactory): | |
protocol = ConnTimerProtocol | |
def __init__(self, host, port): | |
self.deferred = defer.Deferred() | |
self.host = host | |
self.port = port | |
def clientConnectionFailed(self, connector, reason): | |
self.deferred.errback(reason) | |
def handleSuccess(result): | |
print result | |
def handleFailure(failure): | |
print "*** Error:", failure.getErrorMessage() | |
reactor.stop() | |
def time_connection(host, port): | |
ctFactory = ConnTimerFactory(host, port) | |
reactor.connectTCP(host, port, ctFactory) | |
connecting = ctFactory.deferred | |
connecting.addCallback(handleSuccess) | |
connecting.addErrback(handleFailure) | |
reactor.run() | |
if __name__ == "__main__": | |
import sys, os | |
if not len(sys.argv) == 3: | |
print "Usage: conn_timer.py host port" | |
sys.exit(1) | |
host = sys.argv[1] | |
port = int(sys.argv[2]) | |
time_connection(host, port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment