python writes an instance of a simple web server

  • 2020-10-31 21:49:40
  • OfStack

IDE: Pycharm

sever.py


#!/bin/python
#-*- coding: UTF-8 -*-
# The file name: server.py
#create by wzh 2017/10/26
import socket # The import socket The module 
import re
from multiprocessing import Process # Import process module 
# Set the static file root directory 
HTML_ROOT_DIR='./html'
def handle_client(client_socket):
 """ Process client connection requests """
 request_data=client_socket.recv(1024)
 print(request_data)
 request_lines=request_data.splitlines()
 for line in request_lines:
  print(line)
 #'GET / HTTP/1.1'
 request_start_line=request_lines[0].decode("utf-8")
 print("*"*10)
 print(request_start_line)
 # Extract the file name requested by the user 
 file_name=re.match(r"\w+ +(/[^ ]*) ",str(request_start_line)).group(1)
 if "/" == file_name:
  file_name='/index.html'
 # Open the file and read the contents 
 try:
  file=open(HTML_ROOT_DIR+file_name,"rb")
 except IOError:
  response_start_line="HTTP/1.1 404 Not Found\r\n"
  response_heads="Server: My server\r\n"
  response_body="The file not found!"
 else:
  file_data=file.read()
  file.close()
  response_start_line="HTTP/1.1 200 ok\r\n"
  response_heads="Server: My server\r\n"
  response_body=file_data.decode("utf-8")
 response=response_start_line+response_heads+"\r\n"+response_body
 print("response data:",response)
 client_socket.send(bytes(response,"utf-8"))
 client_socket.close()
if __name__=="__main__":   # If you run this file directly, then __name__ for __main__( Run the following program at this point ) Otherwise, the corresponding package name 
 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #  create socket object 
 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
 #host = socket.gethostname() #  Gets the local host name 
 port = 1212 #
 #print(host)
 s.bind(("", port)) #  Binding port 
 s.listen(5)
 while True:
  c,addr=s.accept() # Establish a client connection 
  print(' Connection address ',addr)
  handle_client_process=Process(target=handle_client,args=(c,)) #ALT+ENTER Shortcut key generation function 
  handle_client_process.start()
  c.close()

index.html


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>My Web</title>
</head>
<h1 align="center">welcome!</h1>
<p align="center"> This is a 1 A fantastic website! </p>
<body>
</body>
</html>

Run server py

Enter localhost: 1212 in your browser


Related articles: