Ruby implementation of an asynchronous file download Httpserver Instance _ruby topic

Source: Internet
Author: User

1. Use Ruby Eventmachine and Em-http-server gem to complete a simple httpserver to provide file download functionality

2. Using the Filestreamer of EM to send the file asynchronously, the header is assembled before the file is sent, and then the Filestreamer

Require ' rubygems ' require ' eventmachine ' Require ' Em-http-server ' class HttpHandler < Em::httpserver::server attr_a Ccessor:filename,: FileSize,:p ath def process_http_request #send file async if @http_request_method. to_s =~/get/&A mp;& @http_request_uri. To_s.end_with? (filename) send_data "http/1.1 ok\n" Send_data "server:xiaomi\n" Send_data "connection:keep-alive\n" Send_da Ta "keep-alive:timeout=15\n" Send_data "content-type:application/octet-stream\n" Send_data "Content-disposition:fil Ename= ' #{filename} ' \ n ' send_data ' content-length: #{filesize}\n ' send_data ' \ n ' streamer = Eventmachine::filestream Er.new (self, path) streamer.callback {# file was sent successfully close_connection_after_writing} else RESPO  NSE = EM::D elegatedhttpresponse.new (self) response.status = Response.content_type ' text/html ' response.content = "Package httpserver<br>usage:wget Http://host:port/#{filename}" Response.send_response end enD End Em::run does 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

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: info-contact@alibabacloud.com 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.