Class: LibWebSocket::Frame

Inherits:
Object
  • Object
show all
Defined in:
lib/libwebsocket/frame.rb

Overview

Construct or parse a WebSocket frame.

SYNOPSIS

# Create frame
frame = LibWebSocket::Frame.new('123')
frame.to_s # \x00123\xff

# Parse frames
frame = LibWebSocket::Frame.new
frame.append("123\x00foo\xff56\x00bar\xff789")
frame.next # =>  foo
frame.next # =>  bar

Instance Method Summary collapse

Constructor Details

#initialize(buffer = nil) ⇒ Frame

Returns a new instance of Frame.



17
18
19
# File 'lib/libwebsocket/frame.rb', line 17

def initialize(buffer = nil)
  @buffer = buffer || ''
end

Instance Method Details

#append(string = nil) ⇒ Object

Append a frame chunk.

Examples:

frame.append("\x00foo")
frame.append("bar\xff")


30
31
32
33
34
35
36
37
# File 'lib/libwebsocket/frame.rb', line 30

def append(string = nil)
  return unless string.is_a?(String)

  @buffer += string
  @buffer.force_encoding('ASCII-8BIT') if @buffer.respond_to?(:force_encoding)

  return self
end

#new(buffer = nil) ⇒ Object

Create new frame without modification of current



22
23
24
# File 'lib/libwebsocket/frame.rb', line 22

def new(buffer = nil)
  self.class.new(buffer)
end

#nextObject

Return the next frame.

Examples:

frame.append("\x00foo")
frame.append("\xff\x00bar\xff")

frame.next; # =>  foo
frame.next; # =>  bar


46
47
48
49
50
51
52
53
# File 'lib/libwebsocket/frame.rb', line 46

def next
  return unless @buffer.slice!(/^[^\x00]*\x00(.*?)\xff/nm)

  string = $1
  string.force_encoding('UTF-8') if string.respond_to?(:force_encoding)

  return string
end

#to_sObject

Construct a WebSocket frame.

Examples:

frame = LibWebSocket::Frame.new('foo')
frame.to_s # => \x00foo\xff


59
60
61
62
63
64
65
# File 'lib/libwebsocket/frame.rb', line 59

def to_s
  ary = ["\x00", @buffer.dup, "\xff"]

  ary.collect{ |s| s.force_encoding('UTF-8') if s.respond_to?(:force_encoding) }

  return ary.join
end