Class: Ferrum::Browser::WebSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/ferrum/browser/web_socket.rb

Constant Summary collapse

WEBSOCKET_BUG_SLEEP =
0.01

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#messagesObject (readonly)

Returns the value of attribute messages.



12
13
14
# File 'lib/ferrum/browser/web_socket.rb', line 12

def messages
  @messages
end

#urlObject (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

#closeObject



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 on_message(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 send_message(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