Class: KHL::WebSocket::Client
- Inherits:
-
Object
- Object
- KHL::WebSocket::Client
- Defined in:
- lib/khl/web_socket/client.rb
Overview
Client for the KHL WebSocket API client = KHL::WebSocket.new(token: “bot_token”) Thread.new { client.run } client.message.pop # Get message from queue
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#messages ⇒ Object
readonly
Returns the value of attribute messages.
-
#state ⇒ Object
readonly
Returns the value of attribute state.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Instance Method Summary collapse
-
#initialize(config) ⇒ Client
constructor
A new instance of Client.
-
#run ⇒ Object
Only receive messages from the server.
Constructor Details
#initialize(config) ⇒ Client
Returns a new instance of Client.
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/khl/web_socket/client.rb', line 26 def initialize(config) config[:compress] ||= false @config = config @http_gateway = HTTP::Gateway.new(config) @url = gateway_url @messages = Queue.new @sn = 0 @state = :disconnected @ping_signal = false @resume_signal = false @ws = nil end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
20 21 22 |
# File 'lib/khl/web_socket/client.rb', line 20 def config @config end |
#messages ⇒ Object (readonly)
Returns the value of attribute messages.
20 21 22 |
# File 'lib/khl/web_socket/client.rb', line 20 def @messages end |
#state ⇒ Object (readonly)
Returns the value of attribute state.
20 21 22 |
# File 'lib/khl/web_socket/client.rb', line 20 def state @state end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
20 21 22 |
# File 'lib/khl/web_socket/client.rb', line 20 def url @url end |
Instance Method Details
#run ⇒ Object
Only receive messages from the server
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/khl/web_socket/client.rb', line 41 def run EM.run { Signal.trap("INT") { EventMachine.stop } Signal.trap("TERM") { EventMachine.stop } @ws = Faye::WebSocket::Client.new(gateway_url) @state = :connecting EventMachine.add_periodic_timer(30) do EventMachine.add_timer(6) do if @ping_signal @state = :timeout unless reconnect unless resume @state = :disconnected EventMachine.stop rerun end end end end # Send ping message @ws.send({s: 2, sn: @sn}.to_json) @ping_signal = true end @ws.on :message do |event| raw = config[:compress] ? Zlib::Inflate.inflate(event.data.pack("C*")) : event.data msg = Message.parse(raw) if msg.hello? @state = :connected elsif msg.pong? @ping_signal = false elsif msg.resume_ack? @resume_signal = false elsif msg.reconnect? @state = :reconnecting rerun elsif msg.event? << msg @sn = msg.sn end end } end |