Skip to content

Instantly share code, notes, and snippets.

What would you like to do? find out how long a HTTP server keeps connections open
#!/usr/bin/env python
by Mark Nottingham <>
How long does a given HTTP server hold persistent connections open?
Requires Twisted <>
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.port))
self.transport.write("Connection: keep-alive\r\n")
def connectionLost(self, reason):
if self.connect_time:
time_connected = time.time() - self.connect_time
print "Connected: %2.2f" % time_connected
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() = host
self.port = port
def clientConnectionFailed(self, connector, reason):
def handleSuccess(result):
print result
def handleFailure(failure):
print "*** Error:", failure.getErrorMessage()
def time_connection(host, port):
ctFactory = ConnTimerFactory(host, port)
reactor.connectTCP(host, port, ctFactory)
connecting = ctFactory.deferred
if __name__ == "__main__":
import sys, os
if not len(sys.argv) == 3:
print "Usage: host port"
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.