Class: Eth::Client::Ws

Inherits:
Eth::Client show all
Defined in:
lib/eth/client/ws.rb

Overview

Provides a WS/S-RPC client with automatic reconnection support.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host) ⇒ Ws

Constructor for the WebSocket client. Should not be used; use Eth::Client.create instead.

Parameters:

  • host (String)

    a URI pointing to a WebSocket RPC-API.

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/eth/client/ws.rb', line 46

def initialize(host)
  super
  @uri = URI.parse(host)
  raise ArgumentError, "Unable to parse the WebSocket-URI!" unless %w[ws wss].include?(@uri.scheme)
  @host = @uri.host
  @port = @uri.port
  @ssl = @uri.scheme == "wss"
  @path = build_path(@uri)
  @mutex = Mutex.new
  @socket = nil
  @fragments = nil
end

Instance Attribute Details

#hostObject (readonly)

The host of the WebSocket endpoint.



31
32
33
# File 'lib/eth/client/ws.rb', line 31

def host
  @host
end

#portObject (readonly)

The port of the WebSocket endpoint.



34
35
36
# File 'lib/eth/client/ws.rb', line 34

def port
  @port
end

#sslObject (readonly)

Attribute indicator for SSL.



40
41
42
# File 'lib/eth/client/ws.rb', line 40

def ssl
  @ssl
end

#uriObject (readonly)

The full URI of the WebSocket endpoint, including path.



37
38
39
# File 'lib/eth/client/ws.rb', line 37

def uri
  @uri
end

Instance Method Details

#closevoid

This method returns an undefined value.

Closes the underlying WebSocket connection.



82
83
84
# File 'lib/eth/client/ws.rb', line 82

def close
  @mutex.synchronize { close_socket }
end

#send_request(payload) ⇒ String

Sends an RPC request to the connected WebSocket endpoint.

Parameters:

  • payload (Hash)

    the RPC request parameters.

Returns:

  • (String)

    a JSON-encoded response.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/eth/client/ws.rb', line 63

def send_request(payload)
  attempts = 0
  begin
    attempts += 1
    @mutex.synchronize do
      ensure_socket
      write_frame(@socket, payload)
      return read_message(@socket)
    end
  rescue IOError, SystemCallError => e
    @mutex.synchronize { close_socket }
    retry if attempts < 2
    raise e
  end
end