Class: EventMachine::RubySockets::FileStreamer

Inherits:
Object
  • Object
show all
Defined in:
lib/em-ruby-sockets/file_streamer.rb

Overview

Streams a file over a given TCP connection. It makes use of the fastfilereaderext.so Ruby extension.

class MyFileStreamer < EM::RubySockets::TcpClient
  def post_init
    streamer = EM::RubySockets::FileStreamer.new(self, "/tmp/bigfile.tar.gz")
    streamer.callback {
      # file was sent successfully
      disconnect
    }
    streamer.errback {
      # file could not be sent
      disconnect
    }
    streamer.run
  end
end

Constant Summary collapse

BackpressureLevel =

Wait until next tick to send more data when 50k is still in the outgoing buffer.

50000
ChunkSize =

Send 16k chunks at a time.

16384

Instance Method Summary collapse

Constructor Details

#initialize(connection, filename, args = {}) ⇒ FileStreamer

Constructor.

Parameters:

  • connection

    An EventMachine::RubySockets::TcpClient, EventMachine::RubySockets::TcpServer, EventMachine::RubySockets::TlsClient or EventMachine::RubySockets::TlsServer.

  • filename

    File path.

  • args

    A Hash with options.

Valid options for args:

  • http_chunks

    Use HTTP 1.1 chunked-encoding.



39
40
41
42
43
# File 'lib/em-ruby-sockets/file_streamer.rb', line 39

def initialize connection, filename, args = {}
  @connection = connection
  @filename = filename
  @http_chunks = args[:http_chunks]
end

Instance Method Details

#callback(&block) ⇒ Object

Set the success callback to be executed upon file transfer completion.



46
47
48
# File 'lib/em-ruby-sockets/file_streamer.rb', line 46

def callback &block
  @on_success_block = block
end

#errback(&block) ⇒ Object

Set the error callback (errback) to be executed if file transfer fails. The errback is called by passing a single argument which can be :invalid_file or :disconnected.



52
53
54
# File 'lib/em-ruby-sockets/file_streamer.rb', line 52

def errback &block
  @on_error_block = block
end

#percentage_sentObject

Returns a Float value indicating the file percentage trasferred at this moment.



70
71
72
# File 'lib/em-ruby-sockets/file_streamer.rb', line 70

def percentage_sent
  @mapping ? (@position.to_f / @size)*100 : 0.0
end

#runObject

Start sending the file. This method must be called after setting both the callback and errback blocks.



58
59
60
61
62
63
64
65
66
67
# File 'lib/em-ruby-sockets/file_streamer.rb', line 58

def run
  unless ::File.readable?(@filename) and ::File.file?(@filename)
    do_error :invalid_file
    return false
  end

  @size = ::File.size(@filename)
  stream_with_mapping
  true
end