当前位置:首页 >> 脚本专栏

Ruby使用eventmachine为HTTP服务器添加文件下载功能

思路:
使用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"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://host: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"htmlcode">

gem install rdiscount –platform=ruby 

来测试是否成功。
按照安装步骤,完成了DevKit的安装,非常简单。

然后,再次安装eventmachine:

gem install eventmachine