代码拉取完成,页面将自动刷新
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()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。