🌌 专注Golang,Python语言,云原生,人工智能领域得博主;
💜 过去经历的意义在于引导你,而非定义你;
📢 欢迎点赞 👍 收藏 ⭐留言!
Python编写http-server
01-返回固定页面的数据
import socket
defhandle_client_request(n_socket, client_ip_port):# 5. 接收信息(请求报文)
buf = n_socket.recv(4096)# buf 是请求报文if buf:print(buf.decode())# 6. 发送信息(响应报文)# 6.1 响应行
response_line ='HTTP/1.1 200 OK\r\n'# 6.2 响应头
response_header ='Server:PY\r\nName:Py42\r\n'# 6.3 空行 \r\n# 6.4 响应体(具体的页面数据), 返回 index.html 的页面
f =open('static/index.html','rb')# 读取到是 bytes 类型
data = f.read()
f.close()# 合成响应体
response =(response_line + response_header +'\r\n').encode()+ data
n_socket.send(response)else:print(f'{client_ip_port} 下线了....')# 7. 关闭连接
n_socket.close()if __name__ =='__main__':# 1. 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置端口复用
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,True)# 2. 绑定 IP 和端口
server_socket.bind(("",8989))# 3. 设置监听
server_socket.listen(128)# 4. 阻塞等待客户端的链接whileTrue:
new_socket, ip_port = server_socket.accept()print(f'{ip_port} 连接了....')
handle_client_request(new_socket, ip_port)
server_socket.close()
02-返回指定也页面
import socket
defhandle_client_request(n_socket, client_ip_port):# 5. 接收信息(请求报文)
buf = n_socket.recv(4096)# buf 是请求报文if buf:# print(buf.decode())
buf = buf.decode()
file_name = buf.split(' ',2)[1]print(f'请求的资源为: {file_name}')if file_name =='/':
file_name ='/index.html'# 6. 发送信息(响应报文)# 6.1 响应行
response_line ='HTTP/1.1 200 OK\r\n'# 6.2 响应头
response_header ='Server:PY\r\nName:Py42\r\n'# 6.3 空行 \r\n# 6.4 响应体(具体的页面数据), 返回 index.html 的页面
f =open('static'+ file_name,'rb')# 读取到是 bytes 类型
data = f.read()
f.close()# 合成响应体
response =(response_line + response_header +'\r\n').encode()+ data
n_socket.send(response)else:print(f'{client_ip_port} 下线了....')# 7. 关闭连接
n_socket.close()if __name__ =='__main__':# 1. 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置端口复用
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,True)# 2. 绑定 IP 和端口
server_socket.bind(("",8989))# 3. 设置监听
server_socket.listen(128)# 4. 阻塞等待客户端的链接whileTrue:
new_socket, ip_port = server_socket.accept()print(f'{ip_port} 连接了....')
handle_client_request(new_socket, ip_port)
server_socket.close()
03-处理不存在的页面请求
import socket
defhandle_client_request(n_socket, client_ip_port):# 5. 接收信息(请求报文)
buf = n_socket.recv(4096)# buf 是请求报文if buf:# print(buf.decode())
buf = buf.decode()
file_name = buf.split(' ',2)[1]print(f'请求的资源为: {file_name}')if file_name =='/':
file_name ='/index.html'# 6. 发送信息(响应报文)# 6.1 响应行
response_line ='HTTP/1.1 200 OK\r\n'# 6.2 响应头
response_header ='Server:PY\r\nName:Py42\r\n'# 6.3 空行 \r\n# 6.4 响应体(具体的页面数据), 返回 index.html 的页面try:
f =open('static'+ file_name,'rb')# 读取到是 bytes 类型
data = f.read()
f.close()except FileNotFoundError:
f =open('static/error.html','rb')
data = f.read()
f.close()
response_line ='HTTP/1.1 404 NOT FOUND\r\n'# 合成响应体
response =(response_line + response_header +'\r\n').encode()+ data
n_socket.send(response)else:print(f'{client_ip_port} 下线了....')# 7. 关闭连接
n_socket.close()if __name__ =='__main__':# 1. 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置端口复用
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,True)# 2. 绑定 IP 和端口
server_socket.bind(("",8989))# 3. 设置监听
server_socket.listen(128)# 4. 阻塞等待客户端的链接whileTrue:
new_socket, ip_port = server_socket.accept()print(f'{ip_port} 连接了....')
handle_client_request(new_socket, ip_port)
server_socket.close()
04-静态 web 服务器-多任务版
import socket
import threading
defhandle_client_request(n_socket, client_ip_port):# 5. 接收信息(请求报文)
buf = n_socket.recv(4096)# buf 是请求报文if buf:# print(buf.decode())
buf = buf.decode()
file_name = buf.split(' ',2)[1]print(f'请求的资源为: {file_name}')if file_name =='/':
file_name ='/index.html'# 6. 发送信息(响应报文)# 6.1 响应行
response_line ='HTTP/1.1 200 OK\r\n'# 6.2 响应头
response_header ='Server:PY\r\nName:Py42\r\n'# 6.3 空行 \r\n# 6.4 响应体(具体的页面数据), 返回 index.html 的页面try:
f =open('static'+ file_name,'rb')# 读取到是 bytes 类型
data = f.read()
f.close()except FileNotFoundError:
f =open('static/error.html','rb')
data = f.read()
f.close()
response_line ='HTTP/1.1 404 NOT FOUND\r\n'# 合成响应体
response =(response_line + response_header +'\r\n').encode()+ data
n_socket.send(response)else:print(f'{client_ip_port} 下线了....')# 7. 关闭连接
n_socket.close()if __name__ =='__main__':# 1. 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置端口复用
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,True)# 2. 绑定 IP 和端口
server_socket.bind(("",8989))# 3. 设置监听
server_socket.listen(128)# 4. 阻塞等待客户端的链接whileTrue:
new_socket, ip_port = server_socket.accept()print(f'{ip_port} 连接了....')
sub_thread = threading.Thread(target=handle_client_request, args=(new_socket, ip_port))
sub_thread.start()
server_socket.close()
05-静态 web服务器-面向对象版
import socket
import threading
classHTTPWebServer(object):def__init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind(('',9090))
self.server_socket.listen(128)def__del__(self):
self.server_socket.close()defstart(self):whileTrue:
new_socket, ip_port = self.server_socket.accept()print(f'{ip_port} 连接了.....')
sub_thread = threading.Thread(target=self.handle_client_request, args=(new_socket, ip_port))
sub_thread.start()@staticmethoddefhandle_client_request(n_socket, client_ip_port):# 接收请求报文
buf = n_socket.recv(4096)if buf:
buf = buf.decode()# 转换为 str# 解析资源路径
file_name = buf.split(' ',2)[1]print(f"请求的资源未: {file_name}")if file_name =='/':
file_name ='/index.html'# 6.1 响应行
response_line ='HTTP/1.1 200 OK\r\n'# 6.2 响应头
response_header ='Server:PY\r\nName:Py42\r\n'# 6.3 空行 \r\n# 6.4 响应体(具体的页面数据), 返回 index.html 的页面try:
f =open('static'+ file_name,'rb')# 读取到是 bytes 类型
data = f.read()
f.close()except FileNotFoundError:
f =open('static/error.html','rb')
data = f.read()
f.close()
response_line ='HTTP/1.1 404 NOT FOUND\r\n'# 合成响应体
response =(response_line + response_header +'\r\n').encode()+ data
n_socket.send(response)else:print(f"{client_ip_port} 关闭了")
n_socket.close()if __name__ =='__main__':# 1. 创建服务器对象
web = HTTPWebServer()# 2. 启动服务器
web.start()
06-python 获取终端命令的参数
"""
命令 参数 参数
python3 xxx.py 9898
需求: 获取参数
"""import sys
# sys.argv 类型是列表:print(sys.argv)
07-命令行指定端口启动
import socket
import threading
import sys
classHTTPWebServer(object):def__init__(self, port):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,True)
self.server_socket.bind(('', port))
self.server_socket.listen(128)def__del__(self):
self.server_socket.close()defstart(self):print('服务已启动,等待客户端连接....')whileTrue:
new_socket, ip_port = self.server_socket.accept()print(f'{ip_port} 连接了.....')
sub_thread = threading.Thread(target=self.handle_client_request, args=(new_socket, ip_port))
sub_thread.start()@staticmethoddefhandle_client_request(n_socket, client_ip_port):# 接收请求报文
buf = n_socket.recv(4096)if buf:
buf = buf.decode()# 转换为 str# 解析资源路径
file_name = buf.split(' ',2)[1]print(f"请求的资源未: {file_name}")if file_name =='/':
file_name ='/index.html'# 6.1 响应行
response_line ='HTTP/1.1 200 OK\r\n'# 6.2 响应头
response_header ='Server:PY\r\nName:Py42\r\n'# 6.3 空行 \r\n# 6.4 响应体(具体的页面数据), 返回 index.html 的页面try:
f =open('static'+ file_name,'rb')# 读取到是 bytes 类型
data = f.read()
f.close()except FileNotFoundError:
f =open('static/error.html','rb')
data = f.read()
f.close()
response_line ='HTTP/1.1 404 NOT FOUND\r\n'# 合成响应体
response =(response_line + response_header +'\r\n').encode()+ data
n_socket.send(response)else:print(f"{client_ip_port} 关闭了")
n_socket.close()if __name__ =='__main__':# print('使用方法: python xxx.py 端口号')# 获取命令行参数
buf = sys.argv
iflen(buf)==2:# 代表有两个参数
port =int(buf[1])else:
port =8888print('使用的端口号是:', port)# 1. 创建服务器对象
web = HTTPWebServer(port)# 2. 启动服务器
web.start()
本文转载自: https://blog.csdn.net/weixin_43270713/article/details/122114390
版权归原作者 毛毛是一只狗 所有, 如有侵权,请联系我们删除。
版权归原作者 毛毛是一只狗 所有, 如有侵权,请联系我们删除。