Class: Kontena::Websocket::Client::Connection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/kontena/websocket/client/connection.rb

Constant Summary collapse

FRAME_SIZE =
1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options = {}) ⇒ Connection

Returns a new instance of Connection.

Parameters:

  • url (String)
  • options (Hash) (defaults to: {})


17
18
19
20
21
22
23
24
25
26
# File 'lib/kontena/websocket/client/connection.rb', line 17

def initialize(url, options = {})
  @options = options
  @url = url
  @client = ::WebSocket::Driver.client(self)
  if headers = options[:headers]
    headers.each do |k, v|
      @client.set_header(k, v)
    end
  end
end

Instance Attribute Details

#url ⇒ Object (readonly)

Returns the value of attribute url.



13
14
15
# File 'lib/kontena/websocket/client/connection.rb', line 13

def url
  @url
end

Instance Method Details

#connect ⇒ Object



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

def connect
  uri = URI.parse(@url)
  port = uri.port || (uri.scheme == "ws" ? 80 : 443)
  @socket = ::TCPSocket.new(uri.host, port)
  if uri.scheme == "wss"
    ctx = ::OpenSSL::SSL::SSLContext.new
    ctx.ssl_version = @options[:ssl_version] if @options[:ssl_version]
    ctx.verify_mode = @options[:verify_mode] if @options[:verify_mode]
    cert_store = ::OpenSSL::X509::Store.new
    cert_store.set_default_paths
    ctx.cert_store = cert_store
    @socket = ::OpenSSL::SSL::SSLSocket.new(@socket, ctx)
    @socket.connect
  end
  @client.start
  Thread.new { self.read_socket }
end

#read_socket ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/kontena/websocket/client/connection.rb', line 52

def read_socket
  loop do
    begin
      @client.parse(@socket.readpartial(FRAME_SIZE))
    rescue EOFError
      break
    end
  end
end

#write(buffer) ⇒ Object



48
49
50
# File 'lib/kontena/websocket/client/connection.rb', line 48

def write(buffer)
  @socket.write(buffer)
end