ruby實現的一個非同步檔案下載HttpServer例項

NO IMAGE

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中使用多執行緒佇列(Queue)實現下載部落格文章儲存到本地檔案Ruby中使用mechanize批量下載校內網相簿照片比較不錯的關於ruby的電子書下載地址集合windows和linux下Ruby的下載與安裝Ruby使用eventmachine為HTTP伺服器新增檔案下載功能