Class: CodinRep::Communication

Inherits:
Object
  • Object
show all
Includes:
Timeout
Defined in:
lib/codin_rep/communication.rb

Constant Summary collapse

READ_SIZE =
4096

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host_address, port, timeout_time = 60, max_attempts = 3) ⇒ Communication

Returns a new instance of Communication.



34
35
36
37
38
39
40
# File 'lib/codin_rep/communication.rb', line 34

def initialize(host_address, port, timeout_time=60, max_attempts=3)
  @host_address = host_address
  @port = port
  @timeout_time = timeout_time
  @max_attempts = max_attempts
  @socket = nil
end

Class Method Details

.finalize(socket) ⇒ Object



30
31
32
# File 'lib/codin_rep/communication.rb', line 30

def self.finalize(socket)
  proc { socket.close }
end

Instance Method Details

#closeObject



88
89
90
91
92
93
# File 'lib/codin_rep/communication.rb', line 88

def close
  if @socket
    @socket.close
    @socket = nil
  end
end

#communicate(payload, expected_response_size) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/codin_rep/communication.rb', line 69

def communicate(payload, expected_response_size)
  open_socket if @socket.nil?

  @payload = payload
  @expected_response_size = expected_response_size

  while @attempt < @max_attempts do
    @received_data = nil

    @received_data = send_receive_data(@payload)

    break unless @received_data.nil?
    @attempt += 1
  end

  raise "Timeout error" if @attempt >= @max_attempts
  @received_data
end

#open_socketObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/codin_rep/communication.rb', line 42

def open_socket
  if @socket
    @socket.close
    @socket = nil
  end

  @attempt = 0
  while @attempt < @max_attempts do
    begin
      timeout(@timeout_time) {
        @socket = TCPSocket.open(@host_address, @port)
      }
      # Use a finalizer to close the socket if "self" is going to be
      # destroyed.
      ObjectSpace.define_finalizer( self, self.class.finalize(@socket) )
    rescue Timeout::Error
      @socket = nil
    end
    break if @socket

    @attempt += 1
  end

  raise "Timeout error" if @attempt >= @max_attempts
  @socket
end