一,python搭建
python -m http.server 端口(默认8000)
# socket包
import socket
# 线程包
import threading
# 程序外部向程序传递参数
import sys
# 封装类
class hendle:
# 初始化变量
def __init__(self, prot):
# 1.创建链接对象
self.conn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 复用端口
self.conn_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 2.绑定ip
self.conn_socket.bind(('', prot))
# 3.最大连接数
self.conn_socket.listen(128)
# 函数
def handle_client_request(self, con_socket):
# 必须接收内容
a = con_socket.recv(1024).decode()
# 处理请求 ,动态寻找资源
arr = a.split(' ')
arr1 = arr[1]
if arr1 == '/':
arr1 = 'index.html'
print(arr[1])
try:
# 打开资源文件
with open(f'./{arr1}', 'rb') as f:
file_data = f.read()
except:
# 打开文件失败执行
# 应答行
response_line = "HTTP/1.1 404 not found\r\n"
# 应答头
response_header = "Server:pwb\r\n"
# 应答体
response_body = '404'
# 应答数据
response_data = (response_line + response_header + "\r\n").encode() + response_body.encode()
con_socket.send(response_data)
else:
# 成功打开文件执行
# 应答行
response_line = "HTTP/1.1 200 OK\r\n"
# 应答头
response_header = "Server:pwb\r\n"
# 应答体
response_body = file_data
# 应答数据
response_data = (response_line + response_header + "\r\n").encode() + response_body
con_socket.send(response_data)
finally:
# 不管结果咋样 都关闭链接
con_socket.close()
# 启动函数
def strat(self):
while True:
# 4.接收
con_socket, ip_port = self.conn_socket.accept()
# 创建线程
sub_thread = threading.Thread(target=self.handle_client_request, args=(con_socket,))
# 调用
sub_thread.start()
# 关闭线程
# conn_socket.close()
def main():
# 判断端口
# 判断端口是否 有 2位数
if len(sys.argv) != 2:
print(f'错误 xxx.py 8000')
return
# 判断端口 是否是整数
if not sys.argv[1].isdigit():
print('错误 xxx.py 8000')
return
prot = int(sys.argv[1])
# 初始化 hendle传入端口
my = hendle(prot)
my.strat()
if __name__ == '__main__':
main()
发表评论