Sha256: fe5e09f584e3001c306a6181a32f9e8ae8227891501c3559ee678d37efc95d46

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

require 'thread'

module Noam
  class NoamPlayerException < Exception; end

  class Player
    def initialize(remote_host, remote_port)
      begin
        @socket = TCPSocket.new(remote_host, remote_port)
      rescue Errno::ECONNREFUSED
        raise NoamPlayerException.new("Unable to connect to the Noam server at #{remote_host}:#{remote_port}. Is it running?")
      end

      @queue = Queue.new
      manage_queue_on_thread
    end

    def put(message)
      @queue.push(message)
    end

    def stop
      put(:exit)
      @thread.join
    end

    def stop!
      @thread.exit
    end

    def connected?
      !@disconnected
    end

    private

    def manage_queue_on_thread
      @thread = Thread.new do |t|
        begin
          loop do
            message = @queue.pop
            break if exit?(message)
            print_message(message)
          end
        rescue Errno::EPIPE
          @disconnected = true
        ensure
          @socket.close
        end
      end
    end

    def print_message(message)
      @socket.print(message.noam_encode)
      @socket.flush
    end

    def exit?(message)
      message == :exit
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
noam_lemma-0.2.1.3 lib/noam_lemma/player.rb