Sha256: 6707313a7655d0e53928f3578af89248a8b3ba7e178ad86e7222fb2e4eb80404

Contents?: true

Size: 1.62 KB

Versions: 3

Compression:

Stored size: 1.62 KB

Contents

require 'socket'
require 'json'

module ChainReactor

  # An error raised if there are communication problems with the server.
  class ClientError < StandardError
  end

  # A client for connecting to a chain reactor server.
  class Client
    # The version of the chain reactor server.
    attr_reader :version

    # Create a connection to a chain reactor server at the given address and port.
    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

    # Send hash data to the server as a JSON
    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
    
    # Send a data string to the server
    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

    # Close the client socket.
    def close
      @socket.close
    end
    
    private
    # Connect and check the server response.
    def connect
      intro = @socket.gets
      matches = /^ChainReactor v([\d.]+)/.match(intro)
      if matches
        @version = matches[1]
      else
        @socket.close
        raise ClientError, "Invalid server response: #{intro}"
      end
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chain-reactor-0.2.2 lib/chain-reactor/client.rb
chain-reactor-0.2.1 lib/chain-reactor/client.rb
chain-reactor-0.2.0 lib/chain-reactor/client.rb