webserver.py
import socket
import threading
import sys
import framework
class HttpWebServer(object):
def __init__(self, port):
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口号复用,程序退出端口号立即释放
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 绑定端口号
tcp_server_socket.bind(("", port))
tcp_server_socket.listen(128)
self.tcp_server_socket = tcp_server_socket
# 解决404页面
# 解决多线程访问
@staticmethod
def handle_client_request(new_socket):
recv_data = new_socket.recv(4096)
# 判断接受的数据长度是否为0
if len(recv_data) == 0:
new_socket.close()
return
# 对二进制数据进行解码
recv_content = recv_data.decode("utf-8")
request_list = recv_content.split(" ", maxsplit=2)
request_path = request_list[1]
print(request_path)
if request_path == "/":
request_path = "/index.html"
if request_path.endswith(".html"):
"动态请求资源"
env = {
"request_path": request_path
}
status, headers, response_body = framework.handler_request(env)
print(status, headers, response_body)
# 响应行
response_line = "HTTP/1.1 %s\r\n" % status
# 响应头
response_header = ""
for header in headers:
response_header += "%s:%s\r\n" % header
# 响应报文
response_data = (response_line+
response_header+
"\r\n"+
response_body).encode("utf-8")
# 发送响应报文给浏览器
new_socket.send(response_data)
# 关闭连接
new_socket.close()
else:
try:
with open("website" + request_path, "rb") as file:
file_data = file.read()
except Exception as e:
with open("website/404.html", "rb") as file:
file_data = file.read()
# 响应行
response_line = "HTTP/1.0 404 Not Found\r\n"
# 响应头
response_header = "Server:PWS/1.0\r\n"
# 空行
# 响应体
response_body = file_data
response = (response_line + response_header + "\r\n").encode("utf-8") + response_body
new_socket.send(response)
else:
# 把数据封装成http响应报文格式的数据
# 响应行
response_line = "HTTP/1.0 200 OK\r\n"
# 响应头
response_header = "Server:PWS/1.0\r\n"
# 空行
# 响应体
response_body = file_data
response = (response_line + response_header + "\r\n").encode("utf-8") + response_body
new_socket.send(response)
finally:
new_socket.close()
def start(self):
# 循环等待接受客户端的连接请求
while True:
new_socket, ip_port = self.tcp_server_socket.accept()
sub_threading = threading.Thread(target=self.handle_client_request, args=(new_socket,))
sub_threading.setDaemon(True)
sub_threading.start()
def main():
# params = sys.argv
# print(params)
# if len(params) !=2:
# print("请输入如下格式: python3xxx.py 8000")
# return
# if not params[1].isdigit():
# print("请输入如下格式: python3xxx.py 8000")
# return
# port = int(params[1])
# 创建web服务器
web_server = HttpWebServer(8000)
# 启动服务器
web_server.start()
if __name__ == '__main__':
main()
framework.py
import time
def index():
status = "200 OK"
response_headers = [("Server", "PWS/1.1")]
data = time.ctime()
return status, response_headers, data
def not_found():
status = "404 Not Found"
response_headers = [("Server", "PWS/1.1")]
data = "not found"
return status, response_headers, data
def handler_request(env):
request_path = env["request_path"]
print(request_path)
if request_path == "/index.html":
result = index()
return result
else:
result = not_found()
return result
#