Class: WSDirector::Client

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

Overview

WebSocket client

Constant Summary collapse

WAIT_WHEN_EXPECTING_EVENT =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ignore: nil) ⇒ Client

Create new WebSocket client and connect to WSDirector ws URL.

Optionally provide an ignore pattern (to ignore incoming message, for example, pings)



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/wsdirector/client.rb', line 18

def initialize(ignore: nil)
  @ignore = ignore
  has_messages = @has_messages = Concurrent::Semaphore.new(0)
  messages = @messages = Queue.new
  path = WSDirector.config.ws_url
  open = Concurrent::Promise.new
  client = self

  @id = SecureRandom.hex(6)
  @ws = WebSocket::Client::Simple.connect(path) do |ws|
    ws.on(:open) do |_event|
      open.set(true)
    end

    ws.on :message do |msg|
      data = msg.data
      next if data.empty?
      next if client.ignored?(data)
      messages << data
      has_messages.release
    end

    ws.on :error do |e|
      messages << Error.new("WebSocket Error #{e.inspect} #{e.backtrace}")
    end
  end

  open.wait!(WAIT_WHEN_EXPECTING_EVENT)
rescue Errno::ECONNREFUSED
  raise Error, "Failed to connect to #{path}"
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



11
12
13
# File 'lib/wsdirector/client.rb', line 11

def id
  @id
end

#wsObject (readonly)

Returns the value of attribute ws.



11
12
13
# File 'lib/wsdirector/client.rb', line 11

def ws
  @ws
end

Instance Method Details

#ignored?(msg) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
64
# File 'lib/wsdirector/client.rb', line 61

def ignored?(msg)
  return false unless @ignore
  @ignore.any? { |pattern| msg =~ pattern }
end

#receive(timeout = WAIT_WHEN_EXPECTING_EVENT) ⇒ Object



50
51
52
53
54
55
# File 'lib/wsdirector/client.rb', line 50

def receive(timeout = WAIT_WHEN_EXPECTING_EVENT)
  @has_messages.try_acquire(1, timeout)
  msg = @messages.pop(true)
  raise msg if msg.is_a?(Exception)
  msg
end

#send(msg) ⇒ Object



57
58
59
# File 'lib/wsdirector/client.rb', line 57

def send(msg)
  @ws.send(msg)
end