class Ferrum::Browser::WebSocket
Constants
- SKIP_LOGGING_SCREENSHOTS
- WEBSOCKET_BUG_SLEEP
Attributes
messages[R]
url[R]
Public Class Methods
new(url, max_receive_size, logger)
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 15 def initialize(url, max_receive_size, logger) @url = url @logger = logger uri = URI.parse(@url) @sock = TCPSocket.new(uri.host, uri.port) max_receive_size ||= ::WebSocket::Driver::MAX_LENGTH @driver = ::WebSocket::Driver.client(self, max_length: max_receive_size) @messages = Queue.new if SKIP_LOGGING_SCREENSHOTS @screenshot_commands = Concurrent::Hash.new end @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 if Thread.current.respond_to?(:report_on_exception=) Thread.current.report_on_exception = true end begin while data = @sock.readpartial(512) @driver.parse(data) end rescue EOFError, Errno::ECONNRESET, Errno::EPIPE @messages.close end end @driver.start end
Public Instance Methods
close()
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 89 def close @driver.close end
on_close(_event)
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 68 def on_close(_event) @messages.close @thread.kill end
on_message(event)
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 55 def on_message(event) data = JSON.parse(event.data) @messages.push(data) output = event.data if SKIP_LOGGING_SCREENSHOTS && @screenshot_commands[data["id"]] @screenshot_commands.delete(data["id"]) output.sub!(/{"data":"(.*)"}/, %("Set FERRUM_LOGGING_SCREENSHOTS=true to see screenshots in Base64")) end @logger&.puts(" ◀ #{Ferrum.elapsed_time} #{output}\n") end
on_open(_event)
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 50 def on_open(_event) # https://github.com/faye/websocket-driver-ruby/issues/46 sleep(WEBSOCKET_BUG_SLEEP) end
send_message(data)
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 73 def send_message(data) if SKIP_LOGGING_SCREENSHOTS @screenshot_commands[data[:id]] = true end json = data.to_json @driver.text(json) @logger&.puts("\n\n▶ #{Ferrum.elapsed_time} #{json}") end
write(data)
click to toggle source
# File lib/ferrum/browser/web_socket.rb, line 83 def write(data) @sock.write(data) rescue EOFError, Errno::ECONNRESET, Errno::EPIPE @messages.close end