Class: ChainReactor::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/chain-reactor/client.rb

Overview

A client for connecting to a chain reactor server.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server_addr, server_port) ⇒ Client

Create a connection to a chain reactor server at the given address and port.



16
17
18
19
20
21
22
23
# File 'lib/chain-reactor/client.rb', line 16

def initialize(server_addr,server_port)
  begin
    @socket = TCPSocket.new(server_addr, server_port)
  rescue Errno::ECONNREFUSED
    raise ClientError, "Failed to connect to Chain Reactor server on #{server_addr}:#{server_port}"
  end
  connect
end

Instance Attribute Details

#versionObject (readonly)

The version of the chain reactor server.



13
14
15
# File 'lib/chain-reactor/client.rb', line 13

def version
  @version
end

Instance Method Details

#closeObject

Close the client socket.



46
47
48
# File 'lib/chain-reactor/client.rb', line 46

def close
  @socket.close
end

#send(data_string) ⇒ Object

Send a data string to the server



36
37
38
39
40
41
42
43
# File 'lib/chain-reactor/client.rb', line 36

def send(data_string)
  if data_string.length > 0
    puts "Sending data: #{data_string}"
    @socket.puts data_string
  else
    raise ClientError, 'Cannot send empty data to chain reactor server'
  end
end

#send_as_json(data_hash) ⇒ Object

Send hash data to the server as a JSON



26
27
28
29
30
31
32
33
# File 'lib/chain-reactor/client.rb', line 26

def send_as_json(data_hash)
  if data_hash.length > 0
    json_string = JSON.generate(data_hash)
    send(json_string)
  else
    raise ClientError, 'Cannot send empty data to chain reactor server'
  end
end