思路:
使用ruby eventmachine和em-http-server gem,完成一個簡單的提供文件下載功能的HttpServer;
使用了EM的FileStreamer來非同步發送文件,發送檔案時先組裝了header,然後呼叫FileStreamer。
程式碼:
require 'rubygems' require 'eventmachine' require 'em-http-server' class HTTPHandler < EM::HttpServer::Server attr_accessor :filename, :filesize, :path def process_http_request #send file async if @http_request_method.to_s =~ /GET/ && @http_request_uri.to_s.end_with?(filename) send_data "HTTP/1.1 200 OK\n" send_data "Server: XiaoMi\n" send_data "Connection: Keep-Alive\n" send_data "Keep-Alive: timeout=15\n" send_data "Content-Type: application/octet-stream\n" send_data "Content-Disposition: filename='#{filename}'\n" send_data "Content-Length: #{filesize}\n" send_data "\n" streamer = EventMachine::FileStreamer.new(self, path) streamer.callback { # file was sent successfully close_connection_after_writing } else response = EM::DelegatedHttpResponse.new(self) response.status = 200 response.content_type 'text/html' response.content = "Package HttpServer<br>usage: wget http://www.php.cn/:port/#{filename}" response.send_response end end end EM::run do path = '/tmp/aaa.tar.gz' EM::start_server("0.0.0.0", 8080, HTTPHandler) do |conn| conn.filename = File.basename(path) conn.filesize = File.size(path) conn.path = path end end
#PS:關於eventmachine安裝錯誤的問題
在windows上安裝eventmachine 總是報錯誤:
Building native extensions. This could take a while... ERROR: Error installing eventmachine: ERROR: Failed to build gem native extension.
或其他:
ERROR: Error installing ruby-debug: The 'linecache' native gem requires installed build tools. Please update your PATH to include build tools or download the DevKit from 'http://rubyinstaller.org/downloads' and follow the instructions at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
後來經過了漫長的Google,找到了2個solution:
1.用更低版本的eventmachine
這個提示一直不斷,下面還有一大難錯誤,都是C的編譯錯誤後來網上找了兩個方法
(1)
gem install eventmachine-win32
這個貌似安裝的是較低版本的
(2)gem install
eventmachine --pre
這個看起來像安裝的是beta 1.0.0的。
2.升級devkit
#看了一下,上面沒有提具體的解決方案,但是給出了問題產生的兩個可能原因:
(1)沒有C編譯環境
(2)路徑當中有空格
看看上面的錯誤日誌,發現可能就是編譯環境的問題。於是找了一下。
我的ruby是用one-click installer裝的,版本是1.8.6-p398。
在rubyinstaller的addon頁面,找到了DevKit。
看了一下DevKit的說明:
//Sometimes you just want RubyGems to build that cool native,
//C-based extension without squawking.
//Who's your buddy? DevKit!
看來這就是我需要的。
出錯的原因是安裝eventmachine的時候,需要build tools,但係統中沒有。出錯訊息中同時也給了解決的法案:
(1) 到http://rubyinstaller.org/downloads/ 去下載dev kit – DevKit-tdm-32-4.5.1-20101214-1400-sfx. exe
(2)依照http://github.com/oneclick/rubyinstaller/wiki/Development-Kit/ 安裝dev kit
主要安裝步驟如下:
如果原來系統中已經安裝了舊版的dev kit, 則刪除它
下載上面提到的dev kit
解壓縮下載下來的檔案到指定的目錄,如c:/devkit。 (注意:目錄不能有空格)
運行ruby dk.rb,然後按照提示分別運行ruby dk.rb init 和ruby dk.rb install來增強ruby
可以運行
gem install rdiscount –platform=ruby
來測試是否成功。
依照安裝步驟,完成了DevKit的安裝,非常簡單。
然後,再安裝eventmachine:
gem install eventmachine
更多Ruby使用eventmachine為HTTP伺服器新增檔案下載功能介紹相關文章請關注PHP中文網!