Class: SelfSDK::WebsocketClient

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

Constant Summary collapse

ON_DEMAND_CLOSE_CODE =
3999
CONNECTION_SUPERCEDED =
1011

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.



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

def initialize(url, auto_reconnect, authentication_hook, process_message_hook)
  @url = url
  @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.



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

def ws
  @ws
end

Instance Method Details

#closeObject

Sends a closing message to the websocket client.



62
63
64
65
# File 'lib/messaging.rb', line 62

def close
  SelfSDK.logger.debug "connection closed by the client"
  @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.



71
72
73
# File 'lib/messaging.rb', line 71

def ping
  @ws.ping 'ping'
end

#send(message) ⇒ Object



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

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
# File 'lib/messaging.rb', line 29

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

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

  @ws.on :message do |event|
    @process_message_hook.call(event)
  end

  @ws.on :close do |event|
    SelfSDK.logger.debug "connection closed detected : #{event.code} #{event.reason}"

    if not [ON_DEMAND_CLOSE_CODE, CONNECTION_SUPERCEDED].include? event.code
      raise StandardError('websocket connection closed') if !@auto_reconnect

      if !@reconnection_delay.nil?
        SelfSDK.logger.debug "websocket connection closed (#{event.code}) #{event.reason}"
        sleep @reconnection_delay
        SelfSDK.logger.debug "reconnecting..."
      end

      @reconnection_delay = 3
      start
    end
  end
end