from socket import *
from threading import *
import sys
import traceback
from threading import *
class HTTPSever(object):
def init(self,server_addr,static_dir):
# 增加服务器属性对象
self.server_address=server_addr
self.static_dir=static_dir
self.ip=server_addr[0]
self.port=server_addr[1]
self.create_socket()
# 创建套接字
def create_socket(self):
self.s=socket()
self.s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.s.bind(self.server_address)
def serve_forever(self):
self.s.listen(3) print('监听端口',self.port) while True: try: c,addr=self.s.accept() except KeyboardInterrupt: self.s.close() sys.exit('服务器退出') except Exception: traceback.print_exc() continue # 创建新的线程处理请求 clientThread=Thread(target=self.handlerRequest,args=(c,)) clientThread.setDaemon(True) clientThread.start() def get_html(self,c,getRequest): print() if getRequest=="/": filename=self.static_dir+'/1.html' else: filename=self.static_dir+getRequest try: print(filename) f=open(filename) except IOError: re='HTTP/1.1 404 not found\r\n' re+='\r\n' re+='*****************************' else: re='HTTP/1.1 200 not found\r\n' re+='\r\n' re+=f.read() finally: c.send(re.encode()) def get_data(self,c,getRequest): urls=['/time','/python','/edu'] if getRequest in urls: re='HTTP/1.1 200 ok\r\n' re+='\r\n' if getRequest =='/time': re+='time' elif getRequest=='/edu': re+='edu' elif getRequest=='/python': re+='python' else: re='HTTP/1.1 404 not found\r\n' re+='\r\n' re+='*****************************' c.send(re.encode()) def handlerRequest(self,c): # 接收客户端请求 request=c.recv(4096) requestHeader=request.splitlines() print(requestHeader[0]) # 获取具体内容 getRequest=str(requestHeader[0]).split(' ')[1] if getRequest=='/' or getRequest[-5:]=='.html': self.get_html(c,getRequest) else: self.get_data(c,getRequest) c.close()
if name==“main”:
# 生成对象
server_addr=(’’,8000)
static_dir=’./static’
httpd=HTTPSever(server_addr,static_dir)
# 启动服务器
httpd.serve_forever()
main()