Class: Protocol::WebSocket::Framer

Inherits:
Object
  • Object
show all
Defined in:
lib/protocol/websocket/framer.rb

Overview

Wraps an underlying Async::IO::Stream for reading and writing binary data into structured frames.

Instance Method Summary collapse

Constructor Details

#initialize(stream, frames = FRAMES) ⇒ Framer

Returns a new instance of Framer.



32
33
34
35
# File 'lib/protocol/websocket/framer.rb', line 32

def initialize(stream, frames = FRAMES)
  @stream = stream
  @frames = frames
end

Instance Method Details

#closeObject

Close the underlying stream.



38
39
40
# File 'lib/protocol/websocket/framer.rb', line 38

def close
  @stream.close
end

#flushObject

Flush the underlying stream.



43
44
45
# File 'lib/protocol/websocket/framer.rb', line 43

def flush
  @stream.flush
end

#read_frame(maximum_frame_size = MAXIMUM_ALLOWED_FRAME_SIZE) ⇒ Object

Read a frame from the underlying stream.



49
50
51
52
53
54
55
56
57
58
# File 'lib/protocol/websocket/framer.rb', line 49

def read_frame(maximum_frame_size = MAXIMUM_ALLOWED_FRAME_SIZE)
  # Read the header:
  finished, flags, opcode = read_header
  
  # Read the frame:
  klass = @frames[opcode] || Frame
  frame = klass.read(finished, flags, opcode, @stream, maximum_frame_size)
  
  return frame
end

#read_headerObject

Read the header of the frame.

Raises:

  • (EOFError)


66
67
68
69
70
71
72
# File 'lib/protocol/websocket/framer.rb', line 66

def read_header
  if buffer = @stream.read(1) and buffer.bytesize == 1
    return Frame.parse_header(buffer)
  end
  
  raise EOFError, "Could not read frame header!"
end

#write_frame(frame) ⇒ Object

Write a frame to the underlying stream.



61
62
63
# File 'lib/protocol/websocket/framer.rb', line 61

def write_frame(frame)
  frame.write(@stream)
end