import sysimport socketimport selectimport threading_port = 1234 # Port number to use for listening connection_timeout = 10 # Represents the timeout for the child thread_max_request_size = 4096 # Maximum size of the client's requestvalid_requests = ["POST", "GET", "HEAD"]# Create a connection for listeningdef create_server(port): '''Return a server socket bound to the specified port''' print "Opening socket:", socket.gethostname(), "on Port: ", port connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.setblocking(1) #connection.bind((socket.gethostname(), port)) connection.bind(("", port)) connection.listen(5) return connectiondef send_message(sock, msg): '''Send str msg to the socket sock. A socket.error is raised if the socket cannot accept input.''' total_sent = 0 while total_sent < len(msg): sent = sock.send(msg[total_sent: total_sent + _max_request_size]) total_sent += sent# Handle clientsdef handle_connection(new_socket): # Accept the user's request tmp = new_socket.recv(_max_request_size) request = tmp while request.find("\r\n\r\n") == -1 | request.find("\r\n\'r\'n") ==-1 | request.find("\n\n") ==-1 | request.find("\r\r") == -1 | request.find("\n\r\n") == -1: tmp = new_socket.recv(_max_request_size) request += tmp if len(tmp) == 0: # Connection got closed client_socket.close() print request tokens = strip_it(request) request_type = tokens[0] if request_type not in valid_requests: not_implemented() uri = tokens[1] version = tokens[2] if version != 'HTTP/1.0': new_socket.send("501 Not Implemented\n") print tokens # Set up a connection with the remote server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.connect((uri, 80)) # Change for ports print request # Send the request to the server send_message(server_socket, request) inputs = [new_socket, server_socket] exit = False while not exit: inps, outs, errors = select.select(inputs, [], []) for inp in inps: if inp == new_socket: msg = connection.recv(_max_request_size) if msg == "STOP THIS": exit = True elif inp == server_socket: try: print 'Hi' msg = connection.recv(_max_request_size) print msg except socket.error: exit = True else: print msg # Send it to the client# Establish a connection to remote server# Handle errors# Strip whitespacedef strip_it(string): tokens = string.split() clean_tokens = [] # Clean tokens for token in tokens: clean_tokens.append(token.strip()) return tokensif __name__ == '__main__': # Set up the server connection = create_server(_port) # Send request to remote server # Receive response while 1: (client_socket, address) = connection.accept() # Read user's request try: # Create a new thread, need to use tuple for arguments client = threading.Thread(group = None, target = handle_connection, args = (client_socket,)) client.start() except socket.error: client_socket.close()