#!/usr/bin/env python3 import socket, struct def run_with(connection_class): print ('Testing with', connection_class.__name__, '...') hc = connection_class('httpbin.org') print('Making connection...') hc.connect() print('Changing socket timeout to 2 seconds...') hc.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack('LL', 2, 0)) print('Socket is', hc.sock) print('Making request...') hc.request('GET', '/delay/10') print('Waiting for response, but should be timed out after 2 seconds...') try: hc.getresponse() except http.client.RemoteDisconnected: print('Connection was disconnected - socket timeout.') else: print('Server responded, did not timeout.') print() if __name__ == '__main__': import http.client run_with(http.client.HTTPConnection) run_with(http.client.HTTPSConnection)