Sha256: 4739414a7c5e52d084cbf7edc8b052cb7a20af9561cbf380ca41d9f0a01a28e8

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

module Backport
  class Client
    # @return [Adapter]
    attr_reader :adapter

    def initialize input, output, adapter, remote = {}
      @in = input
      @out = output
      @adapter = make_adapter(adapter, remote)
      @stopped = true
      @buffer = ''
    end

    def stopped?
      @stopped ||= false
    end

    def stop
      return if stopped?
      @adapter.closing
      @stopped = true
    end

    def run
      return unless stopped?
      @stopped = false
      @adapter.opening
      run_input_thread
    end

    def sending data
      @adapter.sending data
    end

    def read
      tmp = nil
      mutex.synchronize do
        tmp = @buffer.dup
        @buffer.clear
      end
      return tmp unless tmp.empty?
    end

    private

    def make_adapter cls_mod, remote
      if cls_mod.is_a?(Class) && cls_mod <= Backport::Adapter
        @adapter = cls_mod.new(@out, remote)
      elsif cls_mod.class == Module
        @adapter = Adapter.new(@out, remote)
        @adapter.extend cls_mod
      else
        raise TypeError, "#{cls_mod} is not a valid Backport adapter"
      end
    end

    def mutex
      @mutex ||= Mutex.new
    end

    def run_input_thread
      Thread.new do
        until stopped?
          @in.flush
          begin
            chars = @in.sysread(255)
          rescue EOFError, Errno::ECONNRESET
            chars = nil
          end
          if chars.nil?
            stop
            break
          end
          mutex.synchronize { @buffer.concat chars }
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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