Class: Ferrum::Browser::WebSocket
- Inherits:
-
Object
- Object
- Ferrum::Browser::WebSocket
- Defined in:
- lib/ferrum/browser/web_socket.rb
Constant Summary collapse
- WEBSOCKET_BUG_SLEEP =
0.01
Instance Attribute Summary collapse
-
#messages ⇒ Object
readonly
Returns the value of attribute messages.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Instance Method Summary collapse
- #close ⇒ Object
-
#initialize(url, logger) ⇒ WebSocket
constructor
A new instance of WebSocket.
- #on_close(_event) ⇒ Object
- #on_message(event) ⇒ Object
- #on_open(_event) ⇒ Object
- #send_message(data) ⇒ Object
- #write(data) ⇒ Object
Constructor Details
#initialize(url, logger) ⇒ WebSocket
Returns a new instance of WebSocket.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/ferrum/browser/web_socket.rb', line 14 def initialize(url, logger) @url = url @logger = logger uri = URI.parse(@url) @sock = TCPSocket.new(uri.host, uri.port) @driver = ::WebSocket::Driver.client(self) @messages = Queue.new @driver.on(:open, &method(:on_open)) @driver.on(:message, &method(:on_message)) @driver.on(:close, &method(:on_close)) @thread = Thread.new do begin while data = @sock.readpartial(512) @driver.parse(data) end rescue EOFError, Errno::ECONNRESET @messages.close end end @thread.priority = 1 @driver.start end |
Instance Attribute Details
#messages ⇒ Object (readonly)
Returns the value of attribute messages.
12 13 14 |
# File 'lib/ferrum/browser/web_socket.rb', line 12 def @messages end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
12 13 14 |
# File 'lib/ferrum/browser/web_socket.rb', line 12 def url @url end |
Instance Method Details
#close ⇒ Object
67 68 69 |
# File 'lib/ferrum/browser/web_socket.rb', line 67 def close @driver.close end |
#on_close(_event) ⇒ Object
52 53 54 55 |
# File 'lib/ferrum/browser/web_socket.rb', line 52 def on_close(_event) @messages.close @thread.kill end |
#on_message(event) ⇒ Object
46 47 48 49 50 |
# File 'lib/ferrum/browser/web_socket.rb', line 46 def (event) data = JSON.parse(event.data) @messages.push(data) @logger&.puts(" ◀ #{event.data}\n") end |
#on_open(_event) ⇒ Object
41 42 43 44 |
# File 'lib/ferrum/browser/web_socket.rb', line 41 def on_open(_event) # https://github.com/faye/websocket-driver-ruby/issues/46 sleep(WEBSOCKET_BUG_SLEEP) end |
#send_message(data) ⇒ Object
57 58 59 60 61 |
# File 'lib/ferrum/browser/web_socket.rb', line 57 def (data) json = data.to_json @driver.text(json) @logger&.puts("\n\n▶ #{json}") end |
#write(data) ⇒ Object
63 64 65 |
# File 'lib/ferrum/browser/web_socket.rb', line 63 def write(data) @sock.write(data) end |