Python implements a simple web server

  • 2021-09-05 00:31:55
  • OfStack


import re
import socket


def service_cilent(new_socket):
  request = new_socket.recv(1024).decode("utf-8")
  # Python splitlines()  By line ('\r', '\r\n', \n') Separate, return 1 A list containing rows as elements, if the parameter  keepends  For  False Does not contain a newline character, if  True The line break is preserved. 
  request_lines = request.splitlines()
  print(request_lines)
  file_name = ""
  ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
  if ret:
    file_name = ret.group(1)
    if file_name == "/":
      file_name = "index.html"
  try:
    f = open(file_name, "rb")
  except:
    response = "HTTP/1.1 404 NOT FOUND\r\n\r\n"
    response += "------file not found-----"
    new_socket.send(response.encode("utf-8"))
  else:
    #  Open the file successfully read the file   Then close the file pointer 
    html_content = f.read()
    f.close()
    #  Data to be sent to the browser ---header
    response = "HTTP/1.1 200 OK\r\n\r\n"
    #  Will response header Send to Browser 
    new_socket.send(response.encode("utf-8"))
    #  Will response body Send to Browser 
    new_socket.send(html_content)
  #  Close the socket 
  new_socket.close()


def main():
  #  Create a socket 
  tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  # tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  #  Binding 
  tcp_server_socket.bind(("", 7089))
  #  Listening socket 
  tcp_server_socket.listen(128)
  while True:
    new_socket, cilent_addr = tcp_server_socket.accept()
    service_cilent(new_socket)
  #  Turn off listening sockets 
  tcp_server_socket.close()


if __name__ == '__main__':
  main()

The above is the Python implementation of a simple web server details, more about python implementation of web server information please pay attention to other related articles on this site!


Related articles: