An asynchronous file download HttpServer instance implemented by ruby,

Source: Internet
Author: User

An asynchronous file download HttpServer instance implemented by ruby,

1. Use ruby eventmachine and em-http-server gem to complete a simple HttpServer that provides the file download function.

2. The FileStreamer of EM is used to send files asynchronously. When the file is sent, the header is assembled and FileStreamer is called.

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 =, path)  streamer.callback {  # file was sent successfully  close_connection_after_writing  } else  response =  response.status = 200  response.content_type 'text/html'  response.content = "Package HttpServer<br>usage: wget http://host:port/#{filename}"  response.send_response end endendEM::run do path = '/tmp/aaa.tar.gz' EM::start_server("", 8080, HTTPHandler) do |conn| conn.filename = File.basename(path) conn.filesize = File.size(path) conn.path = path endend

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.