-
-
Save minhtuanvu/7ee9beeff7bb7bafb4f3ab643066464c to your computer and use it in GitHub Desktop.
Simple HTTP server in Python to test incoming connections
This file contains hidden or 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
| import socket | |
| import logging | |
| import datetime | |
| from BaseHTTPServer import BaseHTTPRequestHandler | |
| from StringIO import StringIO | |
| class HTTPRequest(BaseHTTPRequestHandler): | |
| def __init__(self, request_text): | |
| self.rfile = StringIO(request_text) | |
| self.raw_requestline = self.rfile.readline() | |
| self.error_code = self.error_message = None | |
| self.parse_request() | |
| def send_error(self, code, message): | |
| self.error_code = code | |
| self.error_message = message | |
| logging.basicConfig(filename='server.log',level=logging.DEBUG) | |
| HOST, PORT = '', 8080 | |
| listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| listen_socket.bind((HOST, PORT)) | |
| listen_socket.listen(1) | |
| print 'Serving HTTP on port %s ...' % PORT | |
| while True: | |
| client_connection, client_address = listen_socket.accept() | |
| request = client_connection.recv(1024) | |
| now = datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S.%f") | |
| parsed = HTTPRequest(request) | |
| logging.info(parsed.path.ljust(25) + " " + now + " Got request from " + str(client_address) + " - PEER " + str(client_connection.getpeername()) + " - SOCK " + str(client_connection.getsockname())) | |
| print parsed.path.ljust(25) + " " + now + " Got request from " + str(client_address) + " - PEER " + str(client_connection.getpeername()) + " - SOCK " + str(client_connection.getsockname()) | |
| http_response = """\ | |
| HTTP/1.1 200 OK | |
| This is a test server. | |
| """ | |
| # Comment this line to stop sending http status codes and trigger the multiple connections behaviour in iOS | |
| client_connection.sendall(http_response) | |
| client_connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment