zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Web服务器的底层原理与实现

2023-02-26 12:27:59 时间

import socket, threading, time
from Http.HttpResponse import HttpResponse
from WebFrame.WebFrame import handler_request

class HttpWebServer(object):

(福利推荐:阿里云、腾讯云、华为云服务器最新限时优惠活动,云服务器1核2G仅88元/年、2核4G仅698元/3年,点击这里立即抢购>>>

__run = True def __init__(self, ip_address:str,listen_port: int):     self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     # Set socket reuse ->  True   default:False     self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)     self.server_socket.bind(         (ip_address, listen_port)     )     self.server_socket.listen(128) @staticmethod def handler_http_request(new_socket: socket.socket):     """     :param new_socket:     :return:     """     rec_data = new_socket.recv(4096)     if len(rec_data) == 0:         return     content = rec_data.decode("utf-8")     request_path = content.split(" ", maxsplit=2)[1]     if request_path == '/':         request_path = '/index.html?userCode=wrvvs1rm'     if request_path.endswith(".html?userCode=wrvvs1rm"):         """ ----------------  dynamic  request   ----------------"""         http_response = handler_request(             {"request_path": request_path}         )         new_socket.send(http_response)     else:         """ ----------------  static   request   --------------- """         response_headers, response_body, response_length = None, None, 0         response_status = ''         try:             with open("../static" + request_path, 'rb') as f:                 response_body = f.read()                 response_length: int = len(response_body)                 response_status = HttpResponse.RESPONSE_STATUS_OK         except BaseException as e:             with open('../static/html/404.html?userCode=wrvvs1rm', 'rb') as f:                 response_body = f.read()                 response_length: int = len(response_body)                 response_status = HttpResponse.RESPONSE_STATUS_NOT_FOUND         finally:             local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())             response_headers = f'HTTP/1.1 {response_status}rnContent-Length:{response_length}rnDate:{local_time}rnServer: Pagchern'             response = response_headers.encode("utf-8") + "rn".encode("utf-8") + response_body             new_socket.send(response)     new_socket.close()  def start(self) -> None:     print("Server Start Successful!")     while self.__run:         new_socket, address_info = self.server_socket.accept()         print(f"[+] client {address_info[0]} send request")         sub_thread = threading.Thread(target=HttpWebServer.handler_http_request, args=(new_socket,))         sub_thread.setDaemon(True)         sub_thread.start()  def stop(self) -> None:     self.__run = False     print("Server Stop Successful!") 

if name == ‘__main__’:

server=HttpWebServer('',8888) server.start() 

Web服务器的底层原理与实现


本站部分内容转载自网络,版权属于原作者所有,如有异议请联系QQ153890879修改或删除,谢谢!
转载请注明原文链接:Web服务器的底层原理与实现

你还在原价购买阿里云、腾讯云、华为云、天翼云产品?那就亏大啦!现在申请成为四大品牌云厂商VIP用户,可以3折优惠价购买云服务器等云产品,并且可享四大云服务商产品终身VIP优惠价,还等什么?赶紧点击下面对应链接免费申请VIP客户吧:

1、点击这里立即申请成为腾讯云VIP客户

2、点击这里立即注册成为天翼云VIP客户

3、点击这里立即申请成为华为云VIP客户

4、点击这里立享阿里云产品终身VIP优惠价

喜欢 (0)
[[email protected]]
分享 (0)