Class: WSDirector::Client
- Inherits:
-
Object
- Object
- WSDirector::Client
- Defined in:
- lib/wsdirector/client.rb
Overview
WebSocket client
Constant Summary collapse
- WAIT_WHEN_EXPECTING_EVENT =
5
Instance Attribute Summary collapse
-
#ws ⇒ Object
readonly
Returns the value of attribute ws.
Instance Method Summary collapse
- #ignored?(msg) ⇒ Boolean
-
#initialize(ignore: nil) ⇒ Client
constructor
Create new WebSocket client and connect to WSDirector ws URL.
- #receive(timeout = WAIT_WHEN_EXPECTING_EVENT) ⇒ Object
- #send(msg) ⇒ Object
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)
17 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 |
# File 'lib/wsdirector/client.rb', line 17 def initialize(ignore: nil) @ignore = ignore = @has_messages = Concurrent::Semaphore.new(0) = @messages = Queue.new path = WSDirector.config.ws_url open = Concurrent::Promise.new client = self @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) << data .release end ws.on :error do |e| << 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
#ws ⇒ Object (readonly)
Returns the value of attribute ws.
10 11 12 |
# File 'lib/wsdirector/client.rb', line 10 def ws @ws end |
Instance Method Details
#ignored?(msg) ⇒ Boolean
59 60 61 62 |
# File 'lib/wsdirector/client.rb', line 59 def ignored?(msg) return false unless @ignore @ignore.any? { |pattern| msg =~ pattern } end |
#receive(timeout = WAIT_WHEN_EXPECTING_EVENT) ⇒ Object
48 49 50 51 52 53 |
# File 'lib/wsdirector/client.rb', line 48 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
55 56 57 |
# File 'lib/wsdirector/client.rb', line 55 def send(msg) @ws.send(msg) end |