脚本专栏 
首页 > 脚本专栏 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

思路:
使用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 

上一篇:编写Python爬虫抓取暴走漫画上gif图片的实例分享
下一篇:利用Python获取赶集网招聘信息前篇
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网