Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
http_conn_timer.py: find out how long a HTTP server keeps connections open
#!/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
You can’t perform that action at this time.