Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # simple web server using sockets
- import re
- import socket
- import sys
- import time
- html = """<html>
- <body>
- Hi - this is my html
- </body>
- </html>
- """
- def NBRecv(conn):
- """
- Non blockeing recv from socket.
- return empty string if nothing to recv
- :param conn:
- :return:
- """
- data = ""
- try:
- buf = conn.recv(1024)
- while buf:
- data += buf
- buf = conn.recv(1024)
- except socket.error:
- pass
- return data
- def SendHtml(conn, html):
- """
- Send html header and html text on the connection
- :param conn:
- :param html:
- :return:
- """
- content_len = len(html)
- header = {}
- header["Content-Length"] = str(content_len)
- header["Content-Type"] = "text/html"
- header["Connection"] = "Closed"
- response_line = "HTTP/1.1 200 OK\r\n"
- header_pairs = [k + ": " + v for k,v in header.iteritems()]
- header_text = "\r\n".join(header_pairs)
- header_full = response_line + header_text + "\r\n\r\n"
- conn.send(header_full + html)
- def HandleConnection(conn):
- """
- Handle single connection - parse http request
- :param conn:
- :return:
- """
- # return True if you want to close conn
- request = NBRecv(conn)
- if not request:
- # no data on this connection - keep trying
- return False
- print request
- lines = request.splitlines()
- m = re.match(r"(GET|POST) (/\S*) HTTP/1\.(1|0)", lines[0])
- if not m:
- conn.send("HTTP/1.1 400 Bad Request\r\n")
- return True
- resource = m.group(2)
- if resource != "/":
- conn.send("HTTP/1.1 404 Not found\r\n")
- return True
- SendHtml(conn, html)
- return True
- def HandleConnections(connections):
- for conn in connections:
- if HandleConnection(conn):
- conn.close()
- def WebServer(port):
- accept_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- accept_socket.bind(("", port))
- accept_socket.listen(5)
- accept_socket.setblocking(0)
- connections = []
- while True:
- try:
- conn, addr = accept_socket.accept()
- print 'Connected by', addr
- connections.append(conn)
- except socket.error:
- time.sleep(0) # give some time if no connection waiting
- pass
- HandleConnections(connections)
- def main(argv):
- port = 8081
- if len(argv) > 1:
- port = int(argv[1])
- WebServer(port)
- if __name__ == '__main__':
- sys.exit(main(sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement