2013-03-27 48 views
4

我想寫一個小型的HTTP服務器使用netcat。對於純文本文件,這可以正常工作,但是當我嘗試發送圖片時,瀏覽器僅顯示破碎圖像的圖標。 我所做的是提取所需文件的MIME類型和大小,並將其提供給客戶端。 我的示例圖片的請求的頭看起來是這樣的:服務HTTP響應,包括一個圖像,與netcat

HTTP/1.0 200 OK 
Content-Length: 197677 
Content-Type: image/jpeg 

這是我的bash腳本,我用的netcat工具的-e選項啓動:

#!/bin/bash 

# -- OPTIONS 
index_page=index.htm 
error_page=notfound.htm 

# -- CODE 

# read request 
read -s input 
resource=$(echo $input | grep -P -o '(?<=GET \/).*(?=\)') # extract requested file 
[ ! -n "$resource" ] && resource=$index_page # if no file requested, set to default 
[ ! -f "$resource" ] && resource=$error_page # if requested file not exists, show error pag 

# generate output 
http_content_type=$(file -b --mime-type $resource) # extract mime type 
case "$(echo $http_content_type | cut -d '/' -f2)" in 
    html|plain) 
     output=$(cat $resource) 

     # fix mime type for plain text documents 
     echo $resource | grep -q '.css$' && http_content_type=${http_content_type//plain/css} 
     echo $resource | grep -q '.js$' && http_content_type=${http_content_type//plain/javascript} 
    ;; 

    x-php) 
     output=$(php $resource) 
     http_content_type=${http_content_type//x-php/html} # fix mime type 
    ;; 

    jpeg) 
     output=$(cat $resource) 
    ;; 

    png) 
     output=$(cat $resource) 
    ;; 

    *) 
     echo 'Unknown type' 
esac 

http_content_length="$(echo $output | wc -c | cut -d ' ' -f1)" 

# sending reply 
echo "HTTP/1.0 200 OK" 
echo "Content-Length: $http_content_length" 
echo -e "Content-Type: $http_content_type\n" 
echo $output 

是,如果很開心有人能幫助我:-)

回答

0

我期望二進制數據中的特殊字符在您的shell腳本中處於活動狀態。

我建議你用得到的文件大小:

http_content_length=`stat -c '%s' $resource` 

你與「送」吧:

... 
echo -e "Content-Type: $http_content_type\n" 
cat $resource 
+0

這工作,非常感謝你。我用這個解決方法與輸出變量來解析php代碼,但我會找到一種沒有這個方法 – flappix 2013-03-27 15:47:32

+0

@flappix:創建一個臨時文件,將php輸出寫入它,將$ resource設置爲臨時文件名? – MattH 2013-03-27 15:51:22

+0

我以這種方式解決了這個問題,但是謝謝你對我的幫助。http://ompldr.org/vaHdnYg/httpservera編輯:好的,你的主意比較好,我改變了它;-) thx – flappix 2013-03-27 15:57:24