import socket
import sys
import threading
import time
import gb
import MyFrask
# 开发自己得WEb服务器
class MyHttpServer():
def __init__(self,port):
# 创建新的socket
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#设置端口复用
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
#绑定端口号
server_socket.bind(("",port))
#监听
server_socket.listen(128)
#实参
self.server_socket=server_socket
# 定义处理请求得函数
@staticmethod # 静态方法
def handle_browser_requset(new_socket):
recv_data = new_socket.recv(4096)
if recv_data == 0:
print("未接受到数据")
new_socket.close()
return
# 如果服务端接受的到了数据
request_data = recv_data.decode('utf-8')
print("浏览器请求的数据",request_data)
data_arry = request_data.split(" ", maxsplit=2)
request_path = data_arry[1]
print("请求的数据路径",request_path)
# 如果请求的是根目录
if request_path == "/":
# 默认请求根目录下的index.html
request_path = "/index.html"
# 如果请求的数据是html结尾的
if request_path.endswith(".html"):
# 就是动态资源 ,需要交给框处理
params= {
'request_path' : request_path
}
# 动态资源交给框架,框架有返回值
response = MyFrask.handle_request(params)
new_socket.send(response)
new_socket.close()
else:
# img_path =gb.glob("start/*.jpg") # 这是获取所有图片的路径测试用
# for itme in img_path:
# print(itme)
response_body = None # 响应主体
response_header = None # 响应头
response_first_line = None # 响应头的第一行
response_type = "text/html"
# 如果请求的是静态资源
# 就是请求本地资源 ,人为的把本地资源都放在start 目录中
try:
# 以rb模式打开静态文件下的资源
with open("start" + request_path, "rb") as f: # rb模式是一中i安荣模式 可以是照片视频等
#响应内容
response_body = f.read()
# print(response_body)
#响应头
response_first_line = 'HTTP/1.1 200 ok '
# if request_path.endswith(".jpg"):
# response_type="image/webp"
#相应的主体部分
response_header = "Content-Length:"+str(len(response_body))+"\r\n"+"Content-Type: image/webp ;charset=utf-8\r\n"+"Data:"+time.strftime("%Y-%m-%d %H-%M-%S",time.localtime())+"\r\n"+"Server : 这是xx写的服务器\r\n"
except Exception as e:
with open('start/404.html','rb') as fa:
# 相应主体的页面内容(字节)
response_body= fa.read()
# 响应头(字节) 第一行
response_first_line = 'HTTP/1.1 404 Not Found\r\n'
# 响应头的主题部分
response_header = "Content-Length:"+str(len(response_body))+"\r\n"+"Content-Type:"+ response_type +" ;charset=utf-8\r\n"+"Data:"+time.strftime("%Y-%m-%d %H-%M-%S",time.localtime())+"\r\n"+"Server : 这是尹朝志写的服务器\r\n"
finally:
# 组成响应数据,发送给客户端(浏览器)
# 转成字节数据相加
response = (response_first_line + response_header).encode("utf-8")+response_body
new_socket.send(response)
# 发送玩需要关闭套接字
new_socket.close()
#启动服务器 并且接收请求
def stat(self):
# 循环并且 多线程处理
while True:
#如果有请求就会创建一个新的socket
new_socket,(ip,port)=self.server_socket.accept()
print(f"客户端的IP为{ip},客户端的端口是{port}")
# 一个客户的请求交给一个线程处理
sub_thread = threading.Thread(target=self.handle_browser_requset,args=(new_socket,))
#设置当前线程为守护线程
sub_thread.setDaemon(True)
#启动线程
sub_thread.start()
def main():
Web_server = MyHttpServer(8088)
Web_server.stat()
if __name__ == '__main__':
main()
2 动态资源 放在这里(以动态显示时间为例)
import time
response_type="text/html"
def handle_request(params):
request_path = params["request_path"]
if request_path == '/index.html':
response = index()
return response
else:
# 没有请求得资源 返回404
response = page_not_found()
return response
def index():
# 响应数据
data = time.strftime("%Y-%m-%d %H-%M-%S", time.localtime())
response_body = data
response_first_line = 'HTTP/1.1 200 ok \r\n'
response_header = "Content-Length:" + str(
len(response_body)) + "\r\n" + "Content-Type:" + response_type + " ;charset=utf-8\r\n" + "Data:" + time.strftime(
"%Y-%m-%d %H-%M-%S", time.localtime()) + "\r\n" + "Server : 这是xx写的服务器\r\n"
response = (response_first_line + response_header + response_body).encode("utf-8")
return response
def page_not_found():
with open('start/404.html', 'rb') as fa:
# 相应主体的页面内容(字节)
response_body = fa.read()
# 响应头(字节) 第一行
response_first_line = 'HTTP/1.1 404 Not Found\r\n'
# 响应头的主题部分
response_header = "Content-Length:" + str(
len(response_body)) + "\r\n" + "Content-Type:" + response_type + " ;charset=utf-8\r\n" + "Data:" + time.strftime(
"%Y-%m-%d %H-%M-%S", time.localtime()) + "\r\n" + "Server : 这是xx写的服务器\r\n"
response = (response_first_line + response_header).encode("utf-8") + response_body
return response