web服务器加载静态HTML文件,py文件在浏览器中本地访问。
from socket import *
from multiprocessing import Process
from time import sleep
import re,sys
# 设置静态文件根目录
HTML_ROOT_DIR = "./html"
#动态文件目录
WSGI_PYTHON_DIR = "./wsgipython"
class HttpServer(object):
def __init__(self,port):
self.serSocket = socket(AF_INET, SOCK_STREAM)
self.serSocket.bind(('',port))
self.serSocket.listen(128)
def dealWithClient(self,newSocket,destAddr):
#处理客户端请求:
#while True:
recvData = newSocket.recv(1024)
if len(recvData) > 0:
print('request data:',recvData.decode())
#print('recv[%s]:%s' % (str(destAddr), recvData.decode()))
else:
print('[%s]客户端已经关闭' % str(destAddr))
#break
request_lines = recvData.splitlines()
for line in request_lines:
print(line.decode())
# 解析请求报文
# 'GET / HTTP/1.1'
request_start_line = request_lines[0]
# 提取用户请求的文件名
print("*" * 50)
print(request_start_line.decode("utf-8"))
file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
#动态网页的导入py文件:
if file_name.endswith('.py'):
try:
m=__import__(file_name[1:-3])
except Exception:
self.response_headers = "HTTP/1.1 404 Not Found\r\n"
response_body = "not found!"
else:
env={}
response_body=m.application(env,self.start_response)
response = self.response_headers + "\r\n" + response_body
else:
if "/" == file_name:
file_name = "/index.html"
# 打开文件,读取内容
try:
file = open(HTML_ROOT_DIR + file_name, "rb")
except IOError:
response_start_line = "HTTP/1.1 404 Not Found\r\n"
response_headers = "Server: My server\r\n"
response_body = "The file is not found!"
else:
file_data = file.read()
file.close()
# 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = file_data.decode("utf-8")
response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response)
newSocket.send(response.encode('utf-8'))
newSocket.close()
def start_response(self, status, headers):
response_headers='HTTP/1.1'+status+'\r\n'
for header in headers:
response_headers+='%s:%s\r\n'%header
self.response_headers = response_headers
def main(self):
try:
while True:
print('-----主进程,,等待新客户端的到来------')
newSocket,destAddr =self.serSocket.accept()
print('-----主进程,,接下来负责数据处理[%s]-----'%str(destAddr))
client=Process(target=self.dealWithClient,args=(newSocket,destAddr))
client.start()
newSocket.close() #newSocket.close不在使用recv和send来收发数据
finally:
serSocket.close() #serSocket.close()不在接收新的客户端的链接
if __name__=='__main__':
sys.path.insert(1, WSGI_PYTHON_DIR)
http_server=HttpServer(8000)
http_server.main()