Class: LibWebSocket::Handshake::Client

Inherits:
LibWebSocket::Handshake show all
Defined in:
lib/libwebsocket/handshake/client.rb

Overview

Construct or parse a client WebSocket handshake. This module is written for convenience, since using request and response directly requires the same code again and again.

SYNOPSIS

h = LibWebSocket::Handshake::Client.new(:url => 'ws://example.com')

# Create request
h.to_s # GET /demo HTTP/1.1
       # Upgrade: WebSocket
       # Connection: Upgrade
       # Host: example.com
       # Origin: http://example.com
       # Sec-WebSocket-Key1: 18x 6]8vM;54 *(5:  {   U1]8  z [  8
       # Sec-WebSocket-Key2: 1_ tx7X d  <  nw  334J702) 7]o}` 0
       #
       # Tm[K T2u

# Parse server response
h.parse \<<EOF
HTTP/1.1 101 WebSocket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Location: ws://example.com/demo

fQJ,fN/4F4!~K~MH
EOF

h.error # Check if there were any errors
h.done? # Returns true

Instance Attribute Summary collapse

Attributes inherited from LibWebSocket::Handshake

#error, #secure

Instance Method Summary collapse

Methods inherited from LibWebSocket::Handshake

#req, #res

Constructor Details

#initialize(hash = {}) ⇒ Client

Returns a new instance of Client.



39
40
41
42
43
# File 'lib/libwebsocket/handshake/client.rb', line 39

def initialize(hash = {})
  super

  self.set_url(self.url) if self.url
end

Instance Attribute Details

#urlObject

Returns the value of attribute url.



37
38
39
# File 'lib/libwebsocket/handshake/client.rb', line 37

def url
  @url
end

Instance Method Details

#done?Boolean

Check if response is correct

Returns:

  • (Boolean)


88
89
90
# File 'lib/libwebsocket/handshake/client.rb', line 88

def done?
  res.done?
end

#parse(opts) ⇒ Object

Parse server response

Examples:

h.parse \<<EOF
HTTP/1.1 101 WebSocket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Location: ws://example.com/demo

fQJ,fN/4F4!~K~MH
EOF


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/libwebsocket/handshake/client.rb', line 66

def parse(opts)
  req = self.req
  res = self.res

  unless res.done?
    unless res.parse(opts)
      self.error = res.error
      return
    end

    if res.done?
      if req.version > 75 && req.checksum != res.checksum
        self.error = 'Checksum is wrong.'
        return
      end
    end
  end

  return true
end

#to_sObject

Create request

Examples:

h.to_s # GET /demo HTTP/1.1
       # Upgrade: WebSocket
       # Connection: Upgrade
       # Host: example.com
       # Origin: http://example.com
       # Sec-WebSocket-Key1: 18x 6]8vM;54 *(5:  {   U1]8  z [  8
       # Sec-WebSocket-Key2: 1_ tx7X d  <  nw  334J702) 7]o}` 0
       #
       # Tm[K T2u


103
104
105
# File 'lib/libwebsocket/handshake/client.rb', line 103

def to_s
  req.to_s
end