Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created April 18, 2013 16:20
Show Gist options
  • Save shonenada/5414056 to your computer and use it in GitHub Desktop.
Save shonenada/5414056 to your computer and use it in GitHub Desktop.
A simple web server in python
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
import os
import socket
web_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
web_socket.bind(("127.0.0.1", 8080))
web_socket.listen(5)
WEBROOT = os.getcwd() + "/wwwroot"
while(True):
connection, address = web_socket.accept()
connection.settimeout(60)
msg = connection.recv(2048)
if not msg is None:
path_pattern = re.compile(r"GET (\S+?) HTTP")
resource = path_pattern.findall(msg)
if len(resource) > 0 :
resource = resource[0]
if resource[-1:] == "/":
resource = str(resource) + "index.html"
try:
request_resource = open(WEBROOT + resource, 'rb')
connection.send("HTTP/1.0 200 OK\r\n")
connection.send("Server: aDa webserver\r\n\r\n")
connection.send(request_resource.read())
except(Exception):
connection.send("HTTP/1.1 404 NOT FOUND\r\n")
connection.send("Server: aDa webserver\r\n\r\n")
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment