Created
October 14, 2016 07:49
-
-
Save bonus85/303e914e3c9461c6fdc6343cd57a2bf7 to your computer and use it in GitHub Desktop.
Webserver from scratch
This file contains 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
""" | |
Inspired by: | |
https://ruslanspivak.com/lsbaws-part1/ | |
""" | |
import socket | |
import time | |
HOST = '' | |
TEMPLATE = ( | |
""" | |
HTTP/1.1 {code} OK | |
{body} | |
""" | |
) | |
DEFAULT_BODY = '{"test":"this is a test"}' | |
def main(body, code, delay, port): | |
if body is None: | |
body = DEFAULT_BODY | |
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 | |
try: | |
while True: | |
client_connection, client_address = listen_socket.accept() | |
request = client_connection.recv(1024) | |
print 'Request recieved:\n{}'.format(request) | |
http_response = TEMPLATE.format(code=code, body=body) | |
time.sleep(delay) | |
print 'Sending response:\n{}'.format(http_response) | |
client_connection.sendall(http_response) | |
client_connection.close() | |
except KeyboardInterrupt: | |
pass | |
finally: | |
listen_socket.close() | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser("A bare bones web server") | |
parser.add_argument('-b', '--body', action='store', default=None, | |
help = "Response body") | |
parser.add_argument('-c', '--code', action='store', type=int, default=200, | |
help = "Response code") | |
parser.add_argument('-d', '--delay', action='store', type=int, default=0, | |
help = "Response delay [seconds]") | |
parser.add_argument('-p', '--port', action='store', type=int, default=8888, | |
help = "Port to listen on") | |
opts = parser.parse_args() | |
main(opts.body, opts.code, opts.delay, opts.port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment