Advanced Programming static python web server

  Fixed-data

  import socket

  def request_handler(new_client_socket):

  "" "In response to client requests Kernel" ""

  request_data = new_client_socket.recv(1024)

  # Determine whether the client has been disconnected link

  if not request_data:

  print ( "The client has been disconnected!")

  # Close the current connection

  new_client_socket.close()

  # Exit code is no longer Backward

  return

  # Start stitching response data

  response_line = "HTTP/1.1 200 OK\r\n"

  response_header = "Server:Python-Web1.0\r\n"

  response_blank = "\r\n"

  response_content = "HelloWorld!"

  # Stitching response header

  response_data = response_line + response_header + response_blank + response_content

  # send data

  new_client_socket.send(response_data.encode())

  # Close the socket

  new_client_socket.close()

  def main():

  # Create a socket

  tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

  # Bind IP and port

  tcp_server_socket.bind(("", 8080))

  # Passive socket set socket, the main receiving client link

  tcp_server_socket.listen(128)

  while True:

  # Accept the client links

  new_client_socket, ip_port = tcp_server_socket.accept()

  print ( "[New clients online]", ip_port)

  # Respective client request, transmits the data to the client

  request_handler(new_client_socket)

  if __name__ == '__main__':

  main()

  Fixed-page

  import socket

  def request_handler(new_client_socket):

  "" "In response to client requests Kernel" ""

  request_data = new_client_socket.recv(1024)

  # Determine whether the client has been disconnected link

  if not request_data:

  print ( "The client has been disconnected!")

  # Close the current connection

  new_client_socket.close()

  # Exit code is no longer Backward

  return

  # Start stitching response data

  response_line = "HTTP/1.1 200 OK\r\n"

  response_header = "Server:Python-Web1.0\r\n"

  response_blank = "\r\n"

  # response_content = "HelloWorld!"

  # Read the specified path to the file, and returns

  with open("static/index.html", "rb") as file:

  # Read binary data files

  response_content = file.read()

  # Stitching response header

  response_data = (response_line + response_header + response_blank).encode() + response_content

  # send data

  new_client_socket.send(response_data)

  # Close the socket

  new_client_socket.close()

  def main():

  # Create a socket

  tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

  # Set address reuse

  tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

  # Bind IP and port

  tcp_server_socket.bind(("", 8080))

  # Passive socket set socket, the main receiving client link

  tcp_server_socket.listen(128)

  while True:

  # Accept the client links

  new_client_socket, ip_port = tcp_server_socket.accept()

  print ( "[New clients online]", ip_port)

  # Respective client request, transmits the data to the client

  request_handler(new_client_socket)

  if __name__ == '__main__':

  main()

  Coroutine multi-task servers

  # Import monkey patch

  from gevent import monkey

  import socket

  import re

  import peddled

  # Let gevent recognize general time-consuming operation, and timely handover process

  monkey.patch_all()

  def request_handler(new_client_socket):

  "" "In response to client requests Kernel" ""

  request_data = new_client_socket.recv(1024)

  # Determine whether the client has been disconnected link

  if not request_data:

  print ( "The client has been disconnected!")

  # Close the current connection

  new_client_socket.close()

  # Exit code is no longer Backward

  return

  # The purpose: to give the client request line

  # Client requests for data analysis

  request_data_str = request_data.decode()

  # The "\ r \ n" split request header, each row of memory to obtain a list of requested data

  request_list = request_data_str.split("\r\n")

  # print(request_list)

  # Removed using regular header portion of the request path

  ret = re.search(r"\s(.*)\s", request_list[0])

  if not ret:

  print ( "User Request packet format error!")

  new_client_socket.close()

  return

  # Get path

  path_info = ret.group(1)

  print ( "user request is received:", path_info)

  # Set the default page is index.html request

  if path_info == "/":

  path_info = "/index.html"

  response_header = "Server:Python-Web1.0\r\n"

  response_blank = "\r\n"

  try:

  # Read the specified path to the file, and returns

  with open("static"+path_info, "rb") as file:

  # Read binary data files

  response_content = file.read()

  except Exception as e:

  # Start stitching response data

  response_line = "HTTP/1.1 404 Not Found\r\n"

  response_content = "Error !!! %s" % str(e)

  response_content = response_content.encode()

  else:

  # Start stitching response data

  response_line = "HTTP/1.1 200 OK\r\n"

  # Stitching response header

  response_data = (response_line + response_header + response_blank).encode() + response_content

  # send data

  new_client_socket.send(response_data)

  # Close the socket

  new_client_socket.close()

  def main():

  # Create a socket

  tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

  # Set address reuse

  tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

  # Bind IP and port

  tcp_server_socket.bind(("", 8080))

  # Passive socket set socket, the main receiving client link

  tcp_server_socket.listen(128)

  while True:

  # Accept the client links

  new_client_socket, ip_port = tcp_server_socket.accept()

  print ( "[New clients online]", ip_port)

  # Respective client request, transmits the data to the client

  # request_handler(new_client_socket)

  # Gevent using a client request coroutine

  g1 = gevent.spawn(request_handler, new_client_socket)

  # Because the server has not quit while True, so here is do not join a

  # G1.join () Wuxi flow Which is good http://www.wxbhffk.com/

  if __name__ == '__main__':

  main()

  Package Object Oriented

  # Import module

  import socket

  import re

  import peddled

  from gevent import monkey

  # recv() accept() time.sleep()

  monkey.patch_all()

  class HttpServer(object):

  def __init__(self):

  # Build Tcp server

  # 1, create a socket tcp

  tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

  # Set address reuse

  tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

  # 2, bind ip and port

  tcp_server_socket.bind(("", 8080))

  # 3, the socket by the active set to passive, can only be used to establish a connection socket

  tcp_server_socket.listen(128)

  self.tcp_server_socket = tcp_server_socket

  def start(self):

  # Changed while True purpose is to let the server receives a client request has been

  while True:

  # 4, waiting to accept client connections

  new_client_socket, ip_port = self.tcp_server_socket.accept()

  print ( "[new client came]", ip_port)

  # 5, communication is started, in response to client requests

  # request_handler(new_client_socket)

  # Use gevent multitasking

  g1 = gevent.spawn(self.request_handler, new_client_socket)

  @staticmethod

  def request_handler(new_client_socket):

  "" "Complete response to the client." ""

  # 1, receiving the data sent by the client

  request_data = new_client_socket.recv(1024)

  # 2, to determine whether the data is empty, if given prompt is empty, the program exits

  if not request_data:

  print ( "The client has been disconnected!")

  new_client_socket.close()

  return

  # Returns the specified page

  # 1), obtaining request packet

  request_data_str = request_data.decode()

  # 2), acquiring request line

  With the request packet # \ r \ n segmentation, a list, the list is stored in each entry for each protocol packet

  request_list = request_data_str.split("\r\n")

  # 3), the path resolution request section line

  ret = re.search(r"\s(.*)\s", request_list[0])

  if not ret:

  print ( "User Request packet format error, please try again!")

  new_client_socket.close()

  return

  # Obtaining request packet path

  path_info = ret.group(1)

  # Set the default home page is index.html

  if path_info == "/":

  path_info = "/index.html"

  print ( "is requesting:", path_info)

  # 3, the response data splicing

  # 3.1 response line

  response_line = "HTTP/1.1 200 OK\r\n"

  # 3.2 response headers

  response_header = "Server:PythonWeb v1.0\r\n"

  # 3.3 blank line

  response_blank = "\r\n"

  Content response # 3.4

  # response_content = "HelloWorld!"

  # Client send request, the server returns the segment specified page static / index.html

  # 1) Open the file to read Open

  try:

  with open("./static"+path_info, "rb") as file:

  # 2) reads the contents of the file

  response_content = file.read()

  except Exception as e:

  # Requested page does not exist, you need to do two things: 1) server to catch this exception, otherwise, the server hung up 2) in response to a single customer does not find the requested page

  response_line = "HTTP/1.1 404 Not Found\r\n"

  # If an error occurs, set the response content for Error Information

  response_content = "Error!!!~ %s " % str(e)

  # Coding

  response_content = response_content.encode()

  # 4, splicing the response data, and sends to the client

  response_data = (response_line + response_header + response_blank).encode() + response_content

  new_client_socket.send(response_data)

  # 5, the socket is closed

  new_client_socket.close()

  def main():

  # Instantiate an object

  httpserver = HttpServer()

  # Call the object methods

  httpserver.start()

  # Define main entry

  if __name__ == '__main__':

  main()

Guess you like

Origin www.cnblogs.com/djw12333/p/11459031.html