ruby实现的一个异步文件下载HttpServer实例
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
相关推荐
86193952 2020-10-27
Mynamezhuang 2020-09-18
充满诗意的联盟 2020-08-23
raksmart0 2020-08-17
yfightfors 2020-08-16
84487600 2020-08-16
qdqht00 2020-07-26
WebVincent 2020-07-21
hzyuhz 2020-07-04
fengchao000 2020-07-04
javaraylu 2020-06-28
baijinswpu 2020-06-28
ZHANGRENXIANG00 2020-06-28
Teamomc 2020-06-28
Catastrophe 2020-06-26
hell0kitty 2020-06-17
我欲疾风前行 2020-06-18