Advertisement
franji

Untitled

Jan 24th, 2018
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.53 KB | None | 0 0
  1. # simple web server using sockets
  2.  
  3. import re
  4. import socket
  5. import sys
  6. import time
  7.  
  8. html = """<html>
  9. <body>
  10. Hi - this is my html
  11. </body>
  12. </html>
  13. """
  14.  
  15.  
  16. def NBRecv(conn):
  17.     """
  18.    Non blockeing recv from socket.
  19.    return empty string if nothing to recv
  20.    :param conn:
  21.    :return:
  22.    """
  23.     data = ""
  24.     try:
  25.         buf = conn.recv(1024)
  26.         while buf:
  27.             data += buf
  28.             buf = conn.recv(1024)
  29.     except socket.error:
  30.         pass
  31.     return data
  32.  
  33.  
  34. def SendHtml(conn, html):
  35.     """
  36.    Send html header and html text on the connection
  37.    :param conn:
  38.    :param html:
  39.    :return:
  40.    """
  41.     content_len = len(html)
  42.     header = {}
  43.     header["Content-Length"] = str(content_len)
  44.     header["Content-Type"] = "text/html"
  45.     header["Connection"] = "Closed"
  46.     response_line = "HTTP/1.1 200 OK\r\n"
  47.     header_pairs = [k + ": " + v for k,v in header.iteritems()]
  48.     header_text = "\r\n".join(header_pairs)
  49.     header_full = response_line + header_text + "\r\n\r\n"
  50.     conn.send(header_full + html)
  51.  
  52.  
  53. def HandleConnection(conn):
  54.     """
  55.    Handle single connection - parse http request
  56.    :param conn:
  57.    :return:
  58.    """
  59.     # return True if you want to close conn
  60.     request = NBRecv(conn)
  61.     if not request:
  62.         # no data on this connection - keep trying
  63.         return False
  64.     print request
  65.     lines = request.splitlines()
  66.     m = re.match(r"(GET|POST) (/\S*) HTTP/1\.(1|0)", lines[0])
  67.     if not m:
  68.         conn.send("HTTP/1.1 400 Bad Request\r\n")
  69.         return True
  70.     resource = m.group(2)
  71.     if resource != "/":
  72.         conn.send("HTTP/1.1 404 Not found\r\n")
  73.         return True
  74.     SendHtml(conn, html)
  75.     return True
  76.  
  77.  
  78. def HandleConnections(connections):
  79.     for conn in connections:
  80.         if HandleConnection(conn):
  81.             conn.close()
  82.  
  83. def WebServer(port):
  84.     accept_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  85.     accept_socket.bind(("", port))
  86.     accept_socket.listen(5)
  87.     accept_socket.setblocking(0)
  88.     connections = []
  89.     while True:
  90.         try:
  91.             conn, addr = accept_socket.accept()
  92.             print 'Connected by', addr
  93.             connections.append(conn)
  94.         except socket.error:
  95.             time.sleep(0)  # give some time if no connection waiting
  96.             pass
  97.         HandleConnections(connections)
  98.  
  99.  
  100. def main(argv):
  101.     port = 8081
  102.     if len(argv) > 1:
  103.         port = int(argv[1])
  104.     WebServer(port)
  105.  
  106.  
  107. if __name__ == '__main__':
  108.     sys.exit(main(sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement