Class: Charai::WebSocket

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

Overview

Defined Under Namespace

Classes: DriverImpl

Constant Summary collapse

STATE_CONNECTING =
0
STATE_OPENED =
1
STATE_CLOSING =
2
STATE_CLOSED =
3

Instance Method Summary collapse

Constructor Details

#initialize(url:, max_payload_size: 256 * 1024 * 1024) ⇒ WebSocket

Returns a new instance of WebSocket.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/charai/web_socket.rb', line 60

def initialize(url:, max_payload_size: 256 * 1024 * 1024)
  @impl = DriverImpl.new(url)
  @driver = ::WebSocket::Driver.client(@impl, max_length: max_payload_size)

  setup
  @driver.start

  Thread.new do
    wait_for_data until @ready_state >= STATE_CLOSING
  rescue EOFError
    # Browser was gone.
    # We have nothing todo. Just finish polling.
    if @ready_state < STATE_CLOSING
      handle_on_close(reason: 'Going Away', code: 1001)
    end
  rescue IOError
    # connection closed. Just ignore it.
    raise if @ready_state < STATE_CLOSING
  end
end

Instance Method Details

#close(code: 1000, reason: "") ⇒ Object



111
112
113
114
115
116
# File 'lib/charai/web_socket.rb', line 111

def close(code: 1000, reason: "")
  return if @ready_state >= STATE_CLOSING
  @ready_state = STATE_CLOSING
  @driver.close(reason, code)
  @impl.dispose
end

#on_close(&block) ⇒ Object

Parameters:

  • block (Proc(reason: String, code: Numeric))


123
124
125
# File 'lib/charai/web_socket.rb', line 123

def on_close(&block)
  @on_close = block
end

#on_error(&block) ⇒ Object

Parameters:

  • block (Proc(error_message: String))


128
129
130
# File 'lib/charai/web_socket.rb', line 128

def on_error(&block)
  @on_error = block
end

#on_message(&block) ⇒ Object



132
133
134
# File 'lib/charai/web_socket.rb', line 132

def on_message(&block)
  @on_message = block
end

#on_open(&block) ⇒ Object



118
119
120
# File 'lib/charai/web_socket.rb', line 118

def on_open(&block)
  @on_open = block
end

#send_text(message) ⇒ Object

Parameters:

  • message (String)


106
107
108
109
# File 'lib/charai/web_socket.rb', line 106

def send_text(message)
  return if @ready_state >= STATE_CLOSING
  @driver.text(message)
end