68 lines
2.1 KiB
Python
68 lines
2.1 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
|
||
import http.server
|
||
import socketserver
|
||
import sys
|
||
import os
|
||
|
||
# 设置端口
|
||
PORT = 3000
|
||
|
||
# 自定义请求处理器
|
||
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
||
def log_message(self, format, *args):
|
||
# 自定义日志输出
|
||
sys.stderr.write("%s - - [%s] %s\n" %
|
||
(self.address_string(),
|
||
self.log_date_time_string(),
|
||
format % args))
|
||
|
||
def end_headers(self):
|
||
# 添加CORS头
|
||
self.send_header('Access-Control-Allow-Origin', '*')
|
||
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
||
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
|
||
super().end_headers()
|
||
|
||
def do_OPTIONS(self):
|
||
self.send_response(200)
|
||
self.end_headers()
|
||
|
||
# 主函数
|
||
def main():
|
||
print("=" * 50)
|
||
print("云大阁前端服务器")
|
||
print("=" * 50)
|
||
print(f"正在启动HTTP服务器...")
|
||
print(f"端口: {PORT}")
|
||
print(f"工作目录: {os.getcwd()}")
|
||
print("=" * 50)
|
||
|
||
try:
|
||
# 创建服务器
|
||
with socketserver.TCPServer(("", PORT), MyHTTPRequestHandler) as httpd:
|
||
print(f"\n✓ 服务器启动成功!")
|
||
print(f"✓ 访问地址: http://localhost:{PORT}")
|
||
print(f"✓ 按 Ctrl+C 停止服务器\n")
|
||
print("等待请求...\n")
|
||
|
||
# 开始服务
|
||
httpd.serve_forever()
|
||
|
||
except OSError as e:
|
||
if e.errno == 98 or e.errno == 10048: # Linux是98,Windows是10048
|
||
print(f"\n✗ 错误:端口 {PORT} 已被占用!")
|
||
print(" 请尝试以下操作:")
|
||
print(" 1. 关闭占用该端口的程序")
|
||
print(" 2. 或修改脚本中的PORT变量使用其他端口")
|
||
else:
|
||
print(f"\n✗ 启动失败:{e}")
|
||
except KeyboardInterrupt:
|
||
print("\n\n正在停止服务器...")
|
||
print("✓ 服务器已停止")
|
||
except Exception as e:
|
||
print(f"\n✗ 发生错误:{e}")
|
||
|
||
if __name__ == "__main__":
|
||
main() |