2 dynamic resources are placed here (using dynamic display time as an example).
import socket
import sys
import threading
import time
import gb
import MyFrask
#develop your own WEb server
class MyHttpServer():
def __init__(self,port):
#create new socket
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#set port reuse
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
#bind port number
server_socket.bind(("",port))
#monitoring
server_socket.listen(128)
#actual parameter
self.server_socket=server_socket
#define functions for processing requests
@staticmethod #static method
def handle_browser_requset(new_socket):
recv_data = new_socket.recv(4096)
if recv_data == 0:
print("no data received")
new_socket.close()
return
#if the server receives data
request_data = recv_data.decode('utf-8')
print("browser requested data",request_data)
data_arry = request_data.split(" ", maxsplit=2)
request_path = data_arry[1]
print("the requested data path",request_path)
#if the request is for the root directory
if request_path == "/":
#default request root directory index.html
request_path = "/index.html"
#if the requested data is html ending
if request_path.endswith(".html"):
#it's just a dynamic resource that needs to be handed over to the box for processing
params= {
'request_path' : request_path
}
#dynamic resources are handed over to the framework, which has a return value
response = MyFrask.handle_request(params)
new_socket.send(response)
new_socket.close()
else:
# img_path =gb.glob("start/*.jpg") #this is the path test for obtaining all images
# for itme in img_path:
# print(itme)
response_body = None #response subject
response_header = None #response header
response_first_line = None #the first line of the response header
response_type = "text/html"
#if the request is for static resources
#it's just requesting local resources, artificially placing all local resources in start in the directory
try:
#with rb open resources under static file mode
with open("start" + request_path, "rb") as f: # rb the mode is one i the anrong mode can be photos, videos, etc
#response content
response_body = f.read()
# print(response_body)
#response header
response_first_line = 'HTTP/1.1 200 ok '
# if request_path.endswith(".jpg"):
# response_type="image/webp"
#corresponding main body
response_header = "Content-Length:"+str(len(response_body))+"rn"+"Content-Type: image/webp ;charset=utf-8rn"+"Data:"+time.strftime("%Y-%m-%d %H-%M-%S",time.localtime())+"rn"+"Server : this is xx written server rn"
except Exception as e:
with open('start/404.html','rb') as fa:
#page content of corresponding subject (in bytes)
response_body= fa.read()
#response header (byte) first line
response_first_line = 'HTTP/1.1 404 Not Foundrn'
#the theme section of the response header
response_header = "Content-Length:"+str(len(response_body))+"rn"+"Content-Type:"+ response_type +" ;charset=utf-8rn"+"Data:"+time.strftime("%Y-%m-%d %H-%M-%S",time.localtime())+"rn"+"Server : this is the server written by yin chaozhi rn"
finally:
#compose response data and send it to the client (browser)
#convert to byte data addition
response = (response_first_line + response_header).encode("utf-8")+response_body
new_socket.send(response)
#sending to play requires socket closure
new_socket.close()
#start the server and receive requests
def stat(self):
#loop and multi-threaded processing
while True:
#if there is a request, a new one will be created socket
new_socket,(ip,port)=self.server_socket.accept()
print(f"client's IP for{ ip }the port of the client is{ port}")
#handing a customer's request to a thread for processing
sub_thread = threading.Thread(target=self.handle_browser_requset,args=(new_socket,))
#set the current thread as the guardian thread
sub_thread.setDaemon(True)
#start thread
sub_thread.start()
def main():
Web_server = MyHttpServer(8088)
Web_server.stat()
if __name__== '__main__':
main()