python学习之Web静态服务器
通过近几天学习,完成一个看可以在命令窗口启动,使用命令指定端口的多任务静态web服务区。(这篇文章只附上了主要代码,html文件不附)#!/usr/bin/env python# coding=utf-8import socketimport reimport sysimport geventfrom gevent import monkeymonkey.patch_all...
·
通过近几天学习,完成一个看可以在命令窗口启动,使用命令指定端口的多任务静态web服务区。(这篇文章只附上了主要代码,html文件不附)
#!/usr/bin/env python
# coding=utf-8
import socket
import re
import sys
import gevent
from gevent import monkey
monkey.patch_all()
# 定义服务器类
class HttpWebServer(object):
def __init__(self, port):
# 定义服务端套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端口
tcp_server_socket.bind(('', port))
# 设置端口复用
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 设置监听
tcp_server_socket.listen(128)
print(tcp_server_socket)
# 设置类属性
self.tcp_server_socket = tcp_server_socket
@staticmethod
def open_file(file_path):
with open("static" + file_path, 'rb') as file:
file_data = file.read()
return file_data
# 定义请求处理方法
def handle_http_request(self, service_client_socket):
# 接受数据
client_request = service_client_socket.recv(4096)
# 打印客户端请求
# print(client_request)
# 拿到请求路径
request_line = re.search("/\S*", client_request.decode("utf-8")).group()
print(request_line)
# 判断是否访问index
if request_line == "/":
request_line = "/index.html"
# 打开文件报错
try:
response_body = self.open_file(request_line)
# 定义响应行
response_line = "HTTP/1.1 200 OK\r\n"
except Exception:
# 无法打开文件,就打开404.html
response_body = self.open_file("static/404.html")
# 定义响应行
response_line = "HTTP/1.1 404 Not Found\r\n"
# 定义响应头
response_hearder = "Server: PWS1.0\r\nContent-Type: text/html;charset=utf-8\r\n"
# 拼接响应数据
response_data = (response_line + response_hearder + "\r\n").encode('utf-8') + response_body
# 发送数据
service_client_socket.send(response_data)
# 关闭
service_client_socket.close()
# 定义开始服务的方法
def start(self):
while True:
service_client_socket, ip_port = self.tcp_server_socket.accept()
# print(ip_port)
gevent.spawn(self.handle_http_request, service_client_socket)
def main():
print(sys.argv)
# print(sys.argv[2].isdigit())
print(len(sys.argv))
if len(sys.argv) != 2:
print("参数传递错误,程序终止...")
return
if not sys.argv[1].isdigit():
print("参数传递错误,程序终止...")
return
port = int(sys.argv[1])
http_server = HttpWebServer(port)
http_server.start()
if __name__ == '__main__':
main()
更多推荐
已为社区贡献1条内容
所有评论(0)