Created
February 2, 2015 11:00
-
-
Save mozz100/9cf0d114b4afea1bc058 to your computer and use it in GitHub Desktop.
Very simple web server
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
# A VERY simple (naive?) web server. | |
# Listens for requests (on a socket) and responds with HTML responses. | |
# There are some obvious problems with this (it's really very basic). For instance, | |
# it responds to ALL requests with 200 OK and HTML. | |
# Code based on http://code.activestate.com/recipes/576541-very-simple-http-web-server/ | |
from socket import * | |
HOST = '' # Can put '127.0.0.1' - meaning the local host | |
PORT = 5000 # Arbitrary non-privileged port | |
# Set up a socket to listen on. Options are documented | |
# at https://docs.python.org/2/library/socket.html | |
s = socket(AF_INET,SOCK_STREAM) | |
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) | |
s.bind((HOST, PORT)) | |
# Headers form the first part of every response. | |
headers ='''HTTP/1.0 200 OK | |
Content-Type: text/html | |
''' | |
print "Listening. Point a browser at http://localhost:%d" % PORT | |
s.listen(1) | |
try: | |
# An "everlasting" loop. Can quit with a KeyboardInterrupt (Ctrl+C) | |
while True: | |
# Accept an incoming connection and read up to 1024 bytes | |
conn, addr = s.accept() | |
data = conn.recv(1024) | |
# Output information about the incoming request. | |
print '-' * 100 | |
print 'Connection from ', addr | |
print data[0:100] + "..." | |
print '-' * 100 | |
print "\n" * 3 | |
# Respond with headers + HTML | |
data = headers + "<html><body><h1>Hello</h1></body></html>" | |
conn.send(data) | |
conn.close() | |
except KeyboardInterrupt: | |
print "Stopping..." | |
finally: | |
s.shutdown(1) | |
s.close() | |
print "Done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment