Class: Faye::RackStream

Inherits:
Object
  • Object
show all
Includes:
EventMachine::Deferrable
Defined in:
lib/faye/rack_stream.rb

Direct Known Subclasses

EventSource::Stream, WebSocket::Stream

Defined Under Namespace

Modules: Reader

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ RackStream

Returns a new instance of RackStream.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/faye/rack_stream.rb', line 18

def initialize(socket)
  @socket_object = socket
  @connection    = socket.env['em.connection']
  @stream_send   = socket.env['stream.send']

  @rack_hijack_io = @rack_hijack_io_reader = nil

  hijack_rack_socket

  @connection.socket_stream = self if @connection.respond_to?(:socket_stream)
end

Instance Method Details

#clean_rack_hijackObject



55
56
57
58
59
# File 'lib/faye/rack_stream.rb', line 55

def clean_rack_hijack
  return unless @rack_hijack_io
  @rack_hijack_io_reader.close_connection_after_writing
  @rack_hijack_io = @rack_hijack_io_reader = nil
end

#close_connectionObject



61
62
63
64
# File 'lib/faye/rack_stream.rb', line 61

def close_connection
  clean_rack_hijack
  @connection.close_connection if @connection
end

#close_connection_after_writingObject



66
67
68
69
# File 'lib/faye/rack_stream.rb', line 66

def close_connection_after_writing
  clean_rack_hijack
  @connection.close_connection_after_writing if @connection
end

#each(&callback) ⇒ Object



71
72
73
# File 'lib/faye/rack_stream.rb', line 71

def each(&callback)
  @stream_send ||= callback
end

#failObject



75
76
# File 'lib/faye/rack_stream.rb', line 75

def fail
end

#hijack_rack_socketObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/faye/rack_stream.rb', line 30

def hijack_rack_socket
  return unless @socket_object.env['rack.hijack']

  @socket_object.env['rack.hijack'].call
  @rack_hijack_io = @socket_object.env['rack.hijack_io']
  queue = Queue.new

  EventMachine.schedule do
    begin
      EventMachine.attach(@rack_hijack_io, Reader) do |reader|
        reader.stream = self
        if @rack_hijack_io
          @rack_hijack_io_reader = reader
        else
          reader.close_connection_after_writing
        end
      end
    ensure
      queue.push(nil)
    end
  end

  queue.pop if EventMachine.reactor_running?
end

#receive(data) ⇒ Object



78
79
# File 'lib/faye/rack_stream.rb', line 78

def receive(data)
end

#write(data) ⇒ Object



81
82
83
84
85
86
87
# File 'lib/faye/rack_stream.rb', line 81

def write(data)
  return @rack_hijack_io_reader.send_data(data) if @rack_hijack_io_reader
  return @rack_hijack_io.write(data) if @rack_hijack_io
  return @stream_send.call(data) if @stream_send
rescue => e
  fail if EOFError === e
end