欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-08-28 16:07:03
1.使用ruby eventmachine和em-http-server gem,完成一个简单的提供文件下载功能的httpserver 2.使用了em的filestrea...

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