#socket实现Web服务
#
主程序文件WebServer
import socket
import threading
from sockhandler import SocketHandler
from serverContent import ServerContent
class WebServer():
def __init__(self, ip='127.0.0.1', port=7853):
self.ip = ip
self.port = port
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.ip, self.port))
self.sock.listen(1)
print("WebServer is started............................")
def start(self):
while True:
skt, addr = self.sock.accept()
if skt:
print("Received a socket {0} from {1} ................. ".format(skt.getpeername(), addr))
sockHandler = SocketHandler(skt)
thr = threading.Thread(target=sockHandler.startHandler , args=( ) )
thr.setDaemon(True)
thr.start()
thr.join()
skt.close()
print("Socket {0} handling is done............".format(addr))
if __name__ == '__main__':
ws = WebServer(ip=ServerContent.ip,port=ServerContent.port)
ws.start()
sockHandler文件,包括请求头处理、返回内容处理、路由功能
from serverContent import ServerContent
import os
class SocketHandler:
def __init__(self, sock):
self.sock = sock
def startHandler(self):
self.headHandler()
# self.sendRsp()
# self.sendWebPage('index.html')
self.reqRoute()
return None
def headHandler(self):
# self.headInfo = self.__getAllLine()
# print(self.headInfo)
self.headInfo = dict()
tmpHead = self.__getAllLine()
for line in tmpHead:
if b":" in line:
infos = line.split(b": ")
self.headInfo[infos[0]] = infos[1]
else:
infos = line.split(b" ")
self.headInfo["protocal"] = infos[2]
self.headInfo["method"] = infos[0]
self.headInfo["uri"] = infos[1]
def sendRsp(self):
data = "HELLO WORLD"
self.__sendRspAll(data)
return None
def sendWebPage(self, path):
fp = os.path.join(ServerContent.base_path, path)
with open(fp, mode='r', encoding='utf-8') as f:
html = f.read()
self.__sendRspAll(html)
def sendStaticIco(self, path):
fp = os.path.join(ServerContent.base_ico, path)
with open(fp, mode='rb') as f:
ico = f.read()
self.__sendRspAll(ico)
def reqRoute(self):
uri = self.headInfo.get("uri")
# 拼接webApp文件路径与static路径,来判断用户请求资源是否存在
html_404 = os.path.join(ServerContent.base_path, uri.decode('utf-8'))
ico_404 = os.path.join(ServerContent.base_ico, uri.decode('utf-8'))
# 如果都不存在那就返回404页面
if (not os.path.exists(html_404)) and (not os.path.exists(ico_404)):
print('ERROR')
self.sendWebPage("404.html")
if uri == b"/":
self.sendWebPage("index.html")
if uri == b"/favicon.ico":
self.sendStaticIco("favicon.ico")
if uri == b"/index.html":
self.sendWebPage("index.html")
#####################################
def __getLine(self):
b1 = self.sock.recv(1)
b2 = 0
data = b''
while b2 != b'\r' and b1 != b'\n' :
b2 = b1
b1 = self.sock.recv(1)
data += bytes(b2)
return data.strip(b'\r')
def __getAllLine(self):
data = b''
dataList = list()
data = b''
while True:
data = self.__getLine()
if data:
dataList.append(data)
else:
return dataList
def __sendRspLine(self,data):
if type(data) == bytes:
self.sock.send(data)
else:
data += "\r\n"
self.sock.send(data.encode("utf-8"))
return None
def __sendRspAll(self, data):
self.__sendRspLine(ServerContent.head_protocal+ServerContent.head_code_200+ServerContent.head_status_OK)
strRsp =ServerContent.head_content_length
strRsp += str(len(data))
self.__sendRspLine( strRsp )
self.__sendRspLine(ServerContent.head_content_type+ServerContent.content_type_html)
self.__sendRspLine(ServerContent.blank_line)
self.__sendRspLine(data)
#
配置文件处理sockContent
class ServerContent:
ip = '127.0.0.1'
port = 9999
head_protocal = "HTTP/1.1 "
head_code_200 = "200 "
head_status_OK = "OK"
head_content_length = "Content-Length: "
head_content_type = "Content-Type: "
content_type_html = "text/html"
blank_line = ""
base_path = r'E:\py03\websocket\WebApp'
base_ico = r'E:\py03\websocket\static'
兄弟连学python
Python学习交流、资源共享群:563626388 QQ