1 Star 0 Fork 0

ayercc/AID_2102

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
web_server.py 1.70 KB
一键复制 编辑 原始数据 按行查看 历史
ayercc 提交于 2021-04-20 11:24 . 第一次提交内容
from socket import *
from select import *
import os
class WebServer:
def __init__(self, HOST=None, PORT=None):
self.HOST = HOST
self.PORt = PORT
self.ADDR = (HOST, PORT)
self.rlist = []
self.sock = self.connect()
def connect(self):
sock = socket()
sock.bind(self.ADDR)
return sock
def connect_client(self):
connfd, addr = self.sock.accept()
print('Connect from', addr)
connfd.setblocking(False)
self.rlist.append(connfd)
def show_web(self, connfd, info):
if info == '/':
file_name = './static/' + 'index.html'
else:
file_name = './static/' + info
response = 'HTTP/1.1 200 ok\n'
response += 'Content-Type: text/html\n'
response += '\n'
if os.path.exists(file_name):
file = open(file_name, 'rb')
data = file.read()
connfd.send(response.encode() + data)
else:
data = '404!Sorry!'.encode()
connfd.send(response.encode() + data)
def handle(self, connfd):
request = connfd.recv(1024).decode()
if not request:
return
info = request.split(' ')[1]
self.show_web(connfd, info)
def start(self):
self.sock.listen(5)
self.rlist.append(self.sock)
while True:
rs, ws, xs = select(self.rlist, [], [])
for r in rs:
if r is self.sock:
self.connect_client()
else:
self.handle(r)
self.rlist.remove(r)
r.close()
if __name__ == '__main__':
web = WebServer('0.0.0.0', 8883)
web.start()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ayercc/aid_2102.git
git@gitee.com:ayercc/aid_2102.git
ayercc
aid_2102
AID_2102
master

搜索帮助