ruby実装の非同期ファイルダウンロードHttpServerインスタンス
1744 ワード
1.ruby eventmachineとem-http-server gemを使用して、ファイルダウンロード機能を簡単に提供するHttpServerを完成する
2.EMのFileStreamerを使用して非同期でファイルを送信し、ファイルを送信するときにヘッダを組み立ててからFileStreamerを呼び出す
2.EMのFileStreamerを使用して非同期でファイルを送信し、ファイルを送信するときにヘッダを組み立ててから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
"
send_data "Server: XiaoMi
"
send_data "Connection: Keep-Alive
"
send_data "Keep-Alive: timeout=15
"
send_data "Content-Type: application/octet-stream
"
send_data "Content-Disposition: filename='#{filename}'
"
send_data "Content-Length: #{filesize}
"
send_data "
"
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
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