import socket
def main():
# 1.创建套接字对象
tcp_sever_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 设置端口复用
tcp_sever_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
# 2.绑定端口号
tcp_sever_socket.bind(("",9091))
# 3.设置监听
tcp_sever_socket.listen(128)
# 等待接受客户端的连接请求
while True:
new_client,ip_port = tcp_sever_socket.accept()
# 设置接受数据大小
recv_client_data = new_client.recv(4096)
if len(recv_client_data) == 0:
print("关闭浏览器")
new_client.close()
return
# 对二级制数据进行解码
recv_client_content = recv_client_data.decode("utf-8")
print(recv_client_content)
# 根据指定字符串进行分割,最大分割次数指定2
requests_list = recv_client_content.split(" ",maxsplit=2) # maxsplit 最大分割次数
# 获取请求资源路径
requests_path = requests_list[1]
print(requests_path)
# 判断当前的请求是否是根目录,如果条件成立。返回指定首页数据
if requests_path == "D:":
requests_path = r"D:\One Drive\OneDrive\桌面\python.coding\web全栈\07搭建静态服务器\login.html"
try:
# 动态打开指定文件
with open("login.html","rb") as f:
# 读取文件数据
f_data = f.read()
except Exception as e:
# 请求的资源不存在,返回404数据
# 响应行
response_line = "http/1.1 404 Not Found\r\n"
# 响应头
response_header = "server:PWS1.0\r\n"
with open("error.html",'rb') as file:
file_data = file.read()
# 返回响应体
response_body = file_data
# 拼接响应报文
response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body
# 发送数据
new_client.send(response_data)
else:
# 响应行
response_line = "HTTP/1.1 200 ok\r\n" # \r是回车符 \n 是换行符
# 响应头
response_header = "server:PWS1.0\r\n"
# 响应体
response_body = f_data
# 拼接响应报文
response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body
# 发送数据
new_client.send(response_data)
finally:
# 关闭服务端与客户端的套接字
new_client.close()
if __name__ == '__main__':
main()
静态web服务器-返回指定页面数据
最新推荐文章于 2023-06-22 15:27:16 发布