>  기사  >  백엔드 개발  >  HTTP 서버에 파일 다운로드 기능을 추가하기 위해 eventmachine을 사용하는 Ruby 소개

HTTP 서버에 파일 다운로드 기능을 추가하기 위해 eventmachine을 사용하는 Ruby 소개

高洛峰
高洛峰원래의
2017-03-04 16:13:481531검색

아이디어:

ruby ​​eventmachine 및 em-http-server gem을 사용하여 파일 다운로드 기능을 제공하는 간단한 HttpServer를 완성합니다.
파일을 먼저 비동기적으로 전송하려면 EM의 FileStreamer를 사용하세요. 헤더를 어셈블한 다음 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=&#39;#{filename}&#39;\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 &#39;text/html&#39;
   response.content = "Package HttpServer<br>usage: wget http://www.php.cn/:port/#{filename}"
   response.send_response
  end
 end
 
end
 
EM::run do
 path = &#39;/tmp/aaa.tar.gz&#39;
 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

PS: eventmachine 설치 오류 정보
Windows의 경우 eventmachine 항상 설치 오류 보고:

Building native extensions. This could take a while...
ERROR: Error installing eventmachine:
    ERROR: Failed to build gem native extension.

또는 다른 오류:

ERROR: Error installing ruby-debug:
      The &#39;linecache&#39; native gem requires installed build tools.
   
  Please update your PATH to include build tools or download the DevKit
  from &#39;http://rubyinstaller.org/downloads&#39; and follow the instructions
  at &#39;http://github.com/oneclick/rubyinstaller/wiki/Development-Kit&#39;

Google에서 오랜 검색 끝에 2가지 해결책을 찾았습니다.

1. 낮은 버전의 eventmachine을 사용하세요

이 메시지가 계속 표시되며 아래에 큰 메시지가 있습니다. 어려운 실수, 모두 C 컴파일 오류입니다. 그런데 온라인에서 두 가지 방법을 찾았습니다
(1)

gem install eventmachine-win32

이것은 낮은 버전이 설치된 것 같습니다.
(2)gem install

 eventmachine --pre

베타 1.0.0을 설치한 것 같습니다.


2. Devkit 업그레이드

살펴보니 위에서 언급한 구체적인 해결 방법은 없지만 문제가 발생할 수 있는 두 가지 이유가 나와 있습니다.
(1) 아니요 C 컴파일 환경
(2)
경로에 공백이 있습니다. 위의 에러 로그를 보고 컴파일 환경에 문제가 있을 수 있음을 확인하세요. 그래서 찾아봤습니다.
제 Ruby는 원클릭 설치 프로그램을 사용하여 설치되었으며 버전은 1.8.6-p398입니다.
rubyinstaller의 애드온 페이지에서 DevKit을 찾았습니다.
DevKit 설명을 살펴보세요.

//때때로 RubyGems를 통해 멋진 네이티브
//소리 없이 C 기반 확장 프로그램을 구축하고 싶을 때가 있습니다.
//친구는 누구입니까? ? DevKit!
이것이 나에게 필요한 것 같습니다.

오류가 발생하는 이유는 이벤트머신 설치 시 빌드 도구가 필요한데 시스템에서 사용할 수 없기 때문입니다. 오류 메시지는 해결 방법도 제공합니다.
(1) http://rubyinstaller.org/downloads/로 이동하여 DevKit-tdm-32-4.5.1-20101214-1400-sfx exe를 다운로드합니다. 🎜>(2) http://github.com/oneclick/rubyinstaller/wiki/Development-Kit/을 따라 개발 키트를 설치하세요

주요 설치 단계는 다음과 같습니다.

이미 설치되어 있는 경우 원본 시스템에 설치되어 있는 개발 키트가 이전 버전인 경우 삭제하세요
위에 언급된 개발 키트를 다운로드하세요
다운로드한 파일을 c:/devkit과 같은 특정 디렉터리에 압축을 풉니다. (참고: 디렉토리에는 공백이 포함될 수 없습니다.)
ruby ​​​​dk.rb를 실행한 후, 프롬프트에 따라 ruby ​​​​dk.rb init 및 ruby ​​​​dk.rb install을 각각 실행하여 Ruby ​​

gem install rdiscount –platform=ruby

를 실행하여 성공 여부를 테스트합니다.

설치 단계에 따라 DevKit 설치를 완료하세요. 매우 간단합니다.

그런 다음 eventmachine을 다시 설치하세요.

gem install eventmachine

eventmachine을 사용하여 HTTP 서버에 파일 다운로드 기능을 추가하는 Ruby를 더 보려면 PHP에 주의하세요. 관련 기사는 중국어로!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.