Class: Stream
Instance Attribute Summary collapse
Instance Method Summary
collapse
Methods inherited from Evented
#callbacks, #start, #start_threaded, #stop, #streams, #tick
Constructor Details
#initialize(io) ⇒ Stream
Returns a new instance of Stream.
4
5
6
7
8
9
10
11
12
|
# File 'lib/evented/stream.rb', line 4
def initialize(io)
@io = io
@buffer = ''
streams << self
@_callbacks ||= Hash.new { |hash, key| hash[key] = Array.new }
on(:close) do
close
end
end
|
Instance Attribute Details
#_callbacks ⇒ Object
Returns the value of attribute _callbacks.
2
3
4
|
# File 'lib/evented/stream.rb', line 2
def _callbacks
@_callbacks
end
|
#buffer ⇒ Object
Returns the value of attribute buffer.
2
3
4
|
# File 'lib/evented/stream.rb', line 2
def buffer
@buffer
end
|
Instance Method Details
#close ⇒ Object
51
52
53
54
55
|
# File 'lib/evented/stream.rb', line 51
def close
@io.close
rescue IOError
streams.delete(self)
end
|
#emit(event, *args) ⇒ Object
22
23
24
25
26
|
# File 'lib/evented/stream.rb', line 22
def emit(event, *args)
@_callbacks[event].each do |callback|
callback.call(*args)
end
end
|
#gets ⇒ Object
57
58
59
|
# File 'lib/evented/stream.rb', line 57
def gets
@io.gets
end
|
#handle_read ⇒ Object
28
29
30
31
32
33
34
|
# File 'lib/evented/stream.rb', line 28
def handle_read
chunk = @io.read_nonblock(1024)
emit(:data, chunk)
rescue IO::WaitReadable
rescue EOFError, IOError, Errno::ECONNRESET
emit(:close)
end
|
#handle_write ⇒ Object
36
37
38
39
40
41
42
43
44
|
# File 'lib/evented/stream.rb', line 36
def handle_write
return if @buffer.empty?
@io.write_nonblock(@buffer)
@buffer = ''
emit(:sent)
rescue IO::WaitWritable
rescue EOFError, IOError, Errno::ECONNRESET
emit(:close)
end
|
#on(event, &block) ⇒ Object
18
19
20
|
# File 'lib/evented/stream.rb', line 18
def on(event, &block)
@_callbacks[event] << block
end
|
#send(chunk, &block) ⇒ Object
46
47
48
49
|
# File 'lib/evented/stream.rb', line 46
def send(chunk, &block)
@buffer << chunk
on(:sent, &block) if block_given?
end
|
#to_io ⇒ Object
14
15
16
|
# File 'lib/evented/stream.rb', line 14
def to_io
@io
end
|