Bash编写的GET请求服务器无响应问题求助
Bash编写的GET请求服务器无响应问题求助
各位大佬好,我正在用Bash写一个只处理GET请求的简易服务器,但现在遇到了棘手的问题——当我发送GET请求后,完全收不到任何响应,我实在搞不清哪里出问题了,麻烦帮忙排查一下!
我的脚本代码如下:
#!/bin/bash port=$1 dir=$2 while true; do request=$(nc -w 1 -q 0 -l $port) method=$(echo $request | awk '{print $1}') echo "Method: $method" resource=$(echo $request | awk '{print $2}') echo "Resource: $resource" if [ "$method" != "GET" ]; then echo -e "HTTP/1.1 400 Bad Request\n\n<html><body><h1>400 Bad Request</h1></body></html>" | nc -w 1 -q 0 localhost $port continue fi if [ "$resource" == "/" ]; then resource="/index.html" fi file_path="$dir$resource" if [ ! -r "$file_path" ]; then echo -e "HTTP/1.1 404 Not Found\n\n<html><body><h1>404 Not Found</h1></body></html>" | nc -w 1 -q 0 localhost $port elif [ -d "$file_path" ]; then echo -e "HTTP/1.1 200 OK\n\n<html><body><h1>Index of $resource</h1><hr><pre>$(ls -l $file_path)</pre></body></html>" | nc -w 1 -q 0 localhost $port else echo -e "HTTP/1.1 200 OK\n\n$(cat $file_path)" | nc -w 1 -q 0 localhost $port fi done
我自己尝试过在发送响应的nc命令里加上-l参数,但结果变得很奇怪:第一次请求完全收不到响应,第二次请求反而会收到上一次请求的响应;可如果去掉-l参数,就彻底收不到任何响应了,实在不知道该怎么调整了。
备注:内容来源于stack exchange,提问作者Дима Орлов
相关产品推荐
相关产品推荐

