diff --git a/start_server.sh b/start_server.sh index 7bc727b..1c1fbfe 100755 --- a/start_server.sh +++ b/start_server.sh @@ -11,7 +11,8 @@ PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)" PYTHON="${PYTHON:-$(command -v python3 || command -v python)}" PID_FILE="$PROJECT_DIR/.server.pid" LOG_FILE="/tmp/weread_server.log" -PORT=8080 +# 默认从 8080 启动;也可通过 PORT 或 WEREAD_PORT 指定端口 +PORT="${PORT:-${WEREAD_PORT:-8080}}" cd "$PROJECT_DIR" || exit 1 @@ -22,10 +23,6 @@ is_running() { return 0 fi fi - # 也检查端口是否被占用 - if lsof -i :$PORT -t >/dev/null 2>&1; then - return 0 - fi return 1 } @@ -37,7 +34,27 @@ get_pid() { return fi fi - lsof -i :$PORT -t 2>/dev/null | head -1 + return 0 +} + +find_free_port() { + while lsof -iTCP:"$PORT" -sTCP:LISTEN -t >/dev/null 2>&1; do + PORT=$((PORT + 1)) + done +} + +get_running_port() { + local pid=$(get_pid) + local running_port + + if [ -n "$pid" ]; then + running_port=$(lsof -Pan -p "$pid" -iTCP -sTCP:LISTEN 2>/dev/null \ + | awk 'NR > 1 {print $9}' \ + | sed -E 's/.*:([0-9]+)$/\1/' \ + | head -1) + fi + + echo "${running_port:-$PORT}" } stop_server() { @@ -58,34 +75,43 @@ stop_server() { start_foreground() { if is_running; then - echo "服务已在运行 (PID: $(get_pid))" + local running_port=$(get_running_port) + echo "服务已在运行 (PID: $(get_pid), 端口: $running_port)" + echo "访问地址: http://127.0.0.1:$running_port" exit 1 fi if [ -z "$PYTHON" ]; then echo "未找到可用的 Python 解释器" exit 1 fi - echo "启动服务(前台模式)..." - exec "$PYTHON" app.py + echo "启动服务(前台模式,端口: $PORT)..." + echo "访问地址: http://127.0.0.1:$PORT" + PORT="$PORT" WEREAD_PORT="$PORT" exec "$PYTHON" app.py } start_daemon() { + if [ ! -f "$PID_FILE" ]; then + find_free_port + fi if is_running; then - echo "服务已在运行 (PID: $(get_pid))" + local running_port=$(get_running_port) + echo "服务已在运行 (PID: $(get_pid), 端口: $running_port)" + echo "访问地址: http://127.0.0.1:$running_port" exit 1 fi if [ -z "$PYTHON" ]; then echo "未找到可用的 Python 解释器" exit 1 fi - echo "启动服务(后台守护模式)..." - nohup "$PYTHON" app.py > "$LOG_FILE" 2>&1 & + echo "启动服务(后台守护模式,端口: $PORT)..." + PORT="$PORT" WEREAD_PORT="$PORT" nohup "$PYTHON" app.py > "$LOG_FILE" 2>&1 & local pid=$! echo "$pid" > "$PID_FILE" sleep 2 if kill -0 "$pid" 2>/dev/null; then echo "服务已启动 (PID: $pid)" - echo "访问: http://127.0.0.1:$PORT" + echo "端口: $PORT" + echo "访问地址: http://127.0.0.1:$PORT" echo "日志: $LOG_FILE" else echo "启动失败,请查看日志: $LOG_FILE"