Class: Cod::TcpClient::RobustConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/cod/tcp_client.rb

Overview

A connection that can be down. This allows elegant handling of reconnecting and delaying connections.

Synopsis:

connection = RobustConnection.new('foo:123')
connection.try_connect
connection.write('buffer')
connection.established? # => false
connection.close

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(destination) ⇒ RobustConnection

:nodoc:



187
188
189
190
# File 'lib/cod/tcp_client.rb', line 187

def initialize(destination)
  @destination = destination
  @socket = nil
end

Instance Attribute Details

#destinationObject (readonly)

Returns the value of attribute destination.



192
193
194
# File 'lib/cod/tcp_client.rb', line 192

def destination
  @destination
end

#socketObject (readonly)

Returns the value of attribute socket.



193
194
195
# File 'lib/cod/tcp_client.rb', line 193

def socket
  @socket
end

Instance Method Details

#closeObject

Closes the connection and stops reconnection.



238
239
240
241
# File 'lib/cod/tcp_client.rb', line 238

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

#established?Boolean

Returns true if a connection is currently running.

Returns:

  • (Boolean)


197
198
199
# File 'lib/cod/tcp_client.rb', line 197

def established?
  !! @socket
end

#read(serializer) ⇒ Object

Reads one message from the socket if possible.



224
225
226
227
228
229
230
231
232
233
234
# File 'lib/cod/tcp_client.rb', line 224

def read(serializer)
  return serializer.de(@socket) if @socket
  
  # assert: @socket is still nil, because no connection could be made. 
  # Try to make one
  loop do
    try_connect
    return serializer.de(@socket) if @socket
    sleep 0.01
  end
end

#try_connectObject

Attempt to establish a connection. If there is already a connection and it still seems sound, does nothing.



204
205
206
207
208
209
210
211
# File 'lib/cod/tcp_client.rb', line 204

def try_connect
  return if established?
  
  @socket = TCPSocket.new(*destination.split(':'))
rescue Errno::ECONNREFUSED
  # No one listening? Well.. too bad.
  @socket = nil
end

#write(buffer) ⇒ Object

Writes a buffer to the connection if it is established. Otherwise fails silently.



216
217
218
219
220
# File 'lib/cod/tcp_client.rb', line 216

def write(buffer)
  if @socket
    @socket.write(buffer)
  end
end