Class: WebSocket::Protocol::Client

Inherits:
Hybi show all
Defined in:
lib/websocket/protocol/client.rb

Constant Summary

Constants inherited from Hybi

Hybi::BYTE, Hybi::ERRORS, Hybi::ERROR_CODES, Hybi::FIN, Hybi::FRAGMENTED_OPCODES, Hybi::GUID, Hybi::LENGTH, Hybi::OPCODE, Hybi::OPCODES, Hybi::OPENING_OPCODES, Hybi::RSV1, Hybi::RSV2, Hybi::RSV3

Constants inherited from WebSocket::Protocol

STATES

Instance Attribute Summary

Attributes inherited from WebSocket::Protocol

#protocol, #ready_state

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Hybi

#binary, #close, #frame, #ping, #text, #version

Methods inherited from WebSocket::Protocol

#binary, #close, jruby?, #onclose, #onerror, #onmessage, #onopen, #ping, rbx?, #state, #text

Constructor Details

#initialize(socket, options = {}) ⇒ Client

Returns a new instance of Client.



9
10
11
12
13
14
15
# File 'lib/websocket/protocol/client.rb', line 9

def initialize(socket, options = {})
  super

  @ready_state = -1
  @key         = Client.generate_key
  @accept      = Base64.encode64(Digest::SHA1.digest(@key + GUID)).strip
end

Class Method Details

.generate_keyObject



5
6
7
# File 'lib/websocket/protocol/client.rb', line 5

def self.generate_key
  Base64.encode64((1..16).map { rand(255).chr } * '').strip
end

Instance Method Details

#parse(buffer) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/websocket/protocol/client.rb', line 24

def parse(buffer)
  return super if @ready_state > 0
  message = []
  buffer.each_byte do |data|
    case @ready_state
      when 0 then
        @buffer << data
        if @buffer[-4..-1] == [0x0D, 0x0A, 0x0D, 0x0A]
          if valid?
            open
          else
            @ready_state = 3
            dispatch(:onclose, CloseEvent.new(ERRORS[:protocol_error], ''))
          end
        end
      when 1 then
        message << data
    end
  end
  parse(message) if @ready_state == 1
end

#startObject



17
18
19
20
21
22
# File 'lib/websocket/protocol/client.rb', line 17

def start
  return false unless @ready_state == -1
  @socket.write(handshake_request)
  @ready_state = 0
  true
end