欢迎来到代码驿站!

Ruby

当前位置:首页 > 脚本语言 > Ruby

ruby实现的一个异步文件下载HttpServer实例

时间:2021-03-10 09:25:14|栏目:Ruby|点击:

1.使用ruby eventmachine和em-http-server gem,完成一个简单的提供文件下载功能的HttpServer

2.使用了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://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

上一篇:对优化Ruby on Rails性能的一些办法的探究

栏    目:Ruby

下一篇:深入剖析Ruby设计模式编程中对命令模式的相关使用

本文标题:ruby实现的一个异步文件下载HttpServer实例

本文地址:http://www.codeinn.net/misctech/77890.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有