ruby实现的一个异步文件下载HttpServer实例
1.使用rubyeventmachine和em-http-servergem,完成一个简单的提供文件下载功能的HttpServer
2.使用了EM的FileStreamer来异步发送文件,发送文件时先组装了header,然后调用FileStreamer
require'rubygems'
require'eventmachine'
require'em-http-server'
classHTTPHandler<EM::HttpServer::Server
attr_accessor:filename,:filesize,:path
defprocess_http_request
#sendfileasync
if@http_request_method.to_s=~/GET/&&@http_request_uri.to_s.end_with?(filename)
send_data"HTTP/1.1200OK\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{
#filewassentsuccessfully
close_connection_after_writing
}
else
response=EM::DelegatedHttpResponse.new(self)
response.status=200
response.content_type'text/html'
response.content="PackageHttpServer<br>usage:wgethttp://host:port/#{filename}"
response.send_response
end
end
end
EM::rundo
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热门推荐
10 宝宝新生入学祝福语简短
11 男孩上学祝福语简短英语
12 嫂子生日英语祝福语简短
13 外婆祝福语短句唯美简短
14 田婆婆生日祝福语简短
15 最美婆婆生日祝福语简短
16 钢琴人祝福语女生简短
17 寒露祝福语毕业寄语简短
18 师傅退休蛋糕祝福语简短