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 40 |
# 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 Thread.current.abort_on_exception = true Thread.current.report_on_exception = true if Thread.current.respond_to?(:report_on_exception=) begin while data = @sock.readpartial(512) @driver.parse(data) end rescue EOFError, Errno::ECONNRESET, Errno::EPIPE @messages.close end end @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
70 71 72 |
# File 'lib/ferrum/browser/web_socket.rb', line 70 def close @driver.close end |
#on_close(_event) ⇒ Object
53 54 55 56 |
# File 'lib/ferrum/browser/web_socket.rb', line 53 def on_close(_event) @messages.close @thread.kill end |
#on_message(event) ⇒ Object
47 48 49 50 51 |
# File 'lib/ferrum/browser/web_socket.rb', line 47 def (event) data = JSON.parse(event.data) @messages.push(data) @logger&.puts(" ◀ #{Ferrum.elapsed_time} #{event.data}\n") end |
#on_open(_event) ⇒ Object
42 43 44 45 |
# File 'lib/ferrum/browser/web_socket.rb', line 42 def on_open(_event) # https://github.com/faye/websocket-driver-ruby/issues/46 sleep(WEBSOCKET_BUG_SLEEP) end |
#send_message(data) ⇒ Object
58 59 60 61 62 |
# File 'lib/ferrum/browser/web_socket.rb', line 58 def (data) json = data.to_json @driver.text(json) @logger&.puts("\n\n▶ #{Ferrum.elapsed_time} #{json}") end |
#write(data) ⇒ Object
64 65 66 67 68 |
# File 'lib/ferrum/browser/web_socket.rb', line 64 def write(data) @sock.write(data) rescue EOFError, Errno::ECONNRESET, Errno::EPIPE @messages.close end |