Sha256: a8bd1954c3f38bc037504a21b10e56e9fc60787f19b12695e57021923a3102ac

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 KB

Contents

require 'socket'
require 'json'

module Cinc
  class Client

    def initialize(host: 'localhost', port: 9001)
      @host = host
      @port = port
    end

    def connect
      @socket = Socket.tcp(@host, @port, connect_timeout: 10)
      rescue StandardError => e
        raise ConnectionError.new(e.message)
    end

    def get_airbases
      command = Command.new('get_airbases', {})

      return process_command(command)
    end

    private

    def process_command(command)
      @socket.puts command.to_json
      response = @socket.gets
      raise ConnectionError.new("Connection terminated by server") unless response
      JSON.parse(response)
      rescue StandardError => e
        raise ConnectionError.new(e.message)
    end

    class Command

      attr_accessor :name, :arguments

      def initialize(name, arguments)
        @name = name
        @arguments = arguments
      end

      def to_json
        {
          name: name,
          arguments: arguments
        }.to_json
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cinc-0.2.0 lib/cinc/client.rb