源码:
# -*- coding:utf-8 -*-
#作者:猫先生的早茶
#时间:2019年6月25日
import threading
import time
import socket
import os
class Web():
def __init__(self):
self.html_path = './www'
self.server_addr = ("0.0.0.0",80)
self.timeout = 1
self.buffer = 4096
self.code = 'utf-8'
def start_service(self):
"""开启网页服务"""
#创建服务对象
server = socket.socket()
#绑定服务器地址
server.bind(self.server_addr)
#设置服务器最大处理量1000
server.listen(1000)
while True:
client,addr = server.accept()
threading.Thread(target=self.get_msg,args=(client,)).start()
def get_msg(self,sock):
time.sleep(self.timeout)
#接收书籍并转化为字符串格式
data = (sock.recv(self.buffer).decode(self.code))
print (data)
#提取用户想看的网页
file = data.split('\r\n')[0].split(' ')[1]
print (file)
#检测用户请求的文件名是否省略了,如果省略了,自动补上
if file == '/':
self.read_file(file='index.html',sock=sock)
else:
self.read_file(file=file.replace('/',''),sock=sock)
def read_file(self,file,sock):
#检测用户想看的网页是否存在,存在则返回,不存在,则返回错误页面
if file in os.listdir(self.html_path):
with open (self.html_path+'/'+file,encoding=self.code) as read_object:
self.send_msg(data=read_object.read(),sock=sock,mode='suss')
else:
with open (self.html_path+'/error.html',encoding=self.code) as read_object:
self.send_msg(data=read_object.read(),sock=sock,mode='error')
def send_msg(self,data,sock,mode='suss'):
#成功响应头
suss_repsonse_head = """HTTP/1.0 200 OK\r\nContent-Type: text/html;charset=utf-8\r\n\r\n"""
#失败响应头
error_response_head = """HTTP/1.0 404 OK\r\nContent-Type: text/html;charset=utf-8\r\n\r\n"""
#如果存在对应网页,则以成功方式返回
if mode == 'suss':
sock.send((suss_repsonse_head+data).encode(self.code))
#如果不存在,则以错误方式返回
elif mode == 'error':
sock.send((error_response_head+data).encode(self.code))
sock.close()
def main(self):
self.start_service()
web = Web()
web.main()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>我的网页</title>
</head>
<body>
<h1>恭喜您打开了自己的网站</h1>
</body>
</html>
在www文件夹中创建一个文件,重命名为error.html 。保存内容如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>错误页面</title>
</head>
<body>
<h1>您查找的网页不存在</h1>
</body>
</html>
因篇幅问题不能全部显示,请点此查看更多更全内容