import socket
import re
def parse_http(request):
'''从浏览器解析资源路径'''
# 获取请求行
head_list = re.split(r'\r\n', request)
print(head_list)
request_line = head_list[0]
# 获取请求资源路径
datas = re.split(r' ', request_line)
print(datas)
# 对路径的安全检查
path = datas[1]
if path == '/':
path = '/index.html'
return path
def handel_cli(cli_soc):
'''处理一个客户端请求'''
# 获取请求头
recv_data = cli_soc.recv(1024*4)
print(recv_data)
# 获取用户请求资源路径
path = parse_http(recv_data.decode('utf-8'))
try:
# 读取文件内容
with open('html' + path, 'rb') as file:
file_content = file.read()
# 返回响应数据
response_head = 'HTTP/1.1 200 OK\r\n'
response_head += 'Sever: ItcastSever 1.0\r\n'
response_head += '\r\n'
response_body = file_content
except:
# 读取 404 文件内容
with open('html/404.html', 'rb') as file:
file_content = file.read()
# 处理响应数据
response_head = 'HTTP/1.1 404 NOT FOUND\r\n'
response_head += 'Server: ItcastSever 1.0\r\n'
response_head += '\r\n'
response_body = file_content
cli_soc.send(response_head.encode())
cli_soc.send(response_body)
# 关闭客户端套接字
cli_soc.close()
def main():
'''开发响应浏览器的web服务器'''
# 初始化服务器套接字
serv_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置套接字复用地址
serv_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv_soc.bind(('', 1314))
serv_soc.listen(128)
while True:
# 获取客户端连接
cli_soc, cli_addr = serv_soc.accept()
# 为一个客户端提供服务
handel_cli(cli_soc)
# 关闭服务器套接字
serv_soc.close()
if __name__ == '__main__':
main()
import re
def parse_http(request):
'''从浏览器解析资源路径'''
# 获取请求行
head_list = re.split(r'\r\n', request)
print(head_list)
request_line = head_list[0]
# 获取请求资源路径
datas = re.split(r' ', request_line)
print(datas)
# 对路径的安全检查
path = datas[1]
if path == '/':
path = '/index.html'
return path
def handel_cli(cli_soc):
'''处理一个客户端请求'''
# 获取请求头
recv_data = cli_soc.recv(1024*4)
print(recv_data)
# 获取用户请求资源路径
path = parse_http(recv_data.decode('utf-8'))
try:
# 读取文件内容
with open('html' + path, 'rb') as file:
file_content = file.read()
# 返回响应数据
response_head = 'HTTP/1.1 200 OK\r\n'
response_head += 'Sever: ItcastSever 1.0\r\n'
response_head += '\r\n'
response_body = file_content
except:
# 读取 404 文件内容
with open('html/404.html', 'rb') as file:
file_content = file.read()
# 处理响应数据
response_head = 'HTTP/1.1 404 NOT FOUND\r\n'
response_head += 'Server: ItcastSever 1.0\r\n'
response_head += '\r\n'
response_body = file_content
cli_soc.send(response_head.encode())
cli_soc.send(response_body)
# 关闭客户端套接字
cli_soc.close()
def main():
'''开发响应浏览器的web服务器'''
# 初始化服务器套接字
serv_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置套接字复用地址
serv_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv_soc.bind(('', 1314))
serv_soc.listen(128)
while True:
# 获取客户端连接
cli_soc, cli_addr = serv_soc.accept()
# 为一个客户端提供服务
handel_cli(cli_soc)
# 关闭服务器套接字
serv_soc.close()
if __name__ == '__main__':
main()