Class: SelfSDK::WebsocketClient

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

Constant Summary collapse

ON_DEMAND_CLOSE_CODE =
3999

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, auto_reconnect, authentication_hook, process_message_hook) ⇒ WebsocketClient

Returns a new instance of WebsocketClient.



19
20
21
22
23
24
25
26
# File 'lib/messaging.rb', line 19

def initialize(url, auto_reconnect, authentication_hook, process_message_hook)
  @url = url
  @connected = false
  @reconnection_delay = nil
  @auto_reconnect = auto_reconnect
  @authentication_hook = authentication_hook
  @process_message_hook = process_message_hook
end

Instance Attribute Details

#wsObject

Returns the value of attribute ws.



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

def ws
  @ws
end

Instance Method Details

#closeObject

Sends a closing message to the websocket client.



65
66
67
68
69
# File 'lib/messaging.rb', line 65

def close
  SelfSDK.logger.debug "connection closed by the client"
  @connected = false
  @ws.close(ON_DEMAND_CLOSE_CODE, "connection closed by the client")
end

#pingObject

Sends a ping message to the websocket server, but does not expect response. This is kind of a hack to catch some corner cases where the websocket client is not aware it has been disconnected.



75
76
77
# File 'lib/messaging.rb', line 75

def ping
  @ws.ping 'ping'
end

#send(message) ⇒ Object



79
80
81
82
83
# File 'lib/messaging.rb', line 79

def send(message)
  raise "client is not started, refer to start method on the main client" if @ws.nil?

  @ws.send(message.to_fb.bytes)
end

#startObject

Creates a websocket connection and sets up its callbacks.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/messaging.rb', line 29

def start
  SelfSDK.logger.debug "starting listener"
  @ws = Faye::WebSocket::Client.new(@url)
  SelfSDK.logger.debug "initialized"
  @connected = true

  @ws.on :open do |_event|
    SelfSDK.logger.debug "websocket connection established"
    @authentication_hook.call
  end

  @ws.on :message do |event|
    return if !@connected
    
    @process_message_hook.call(event)
  end

  @ws.on :close do |event|
    if @connected
      if ![ON_DEMAND_CLOSE_CODE].include? event.code
        raise StandardError('websocket connection closed') if !@auto_reconnect

        if !@reconnection_delay.nil?
          SelfSDK.logger.debug "waiting #{@reconnection_delay} before "
          sleep @reconnection_delay
        end

        @reconnection_delay = 3
        SelfSDK.logger.debug "reconnecting..."
        start
      end
    end
  end
end