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:



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

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

Instance Attribute Details

#destinationObject (readonly)

Returns the value of attribute destination.



195
196
197
# File 'lib/cod/tcp_client.rb', line 195

def destination
  @destination
end

#socketObject (readonly)

Returns the value of attribute socket.



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

def socket
  @socket
end

Instance Method Details

#closeObject

Closes the connection and stops reconnection.



241
242
243
244
# File 'lib/cod/tcp_client.rb', line 241

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

#established?Boolean

Returns true if a connection is currently running.

Returns:

  • (Boolean)


200
201
202
# File 'lib/cod/tcp_client.rb', line 200

def established?
  !! @socket
end

#read(serializer) ⇒ Object

Reads one message from the socket if possible.



227
228
229
230
231
232
233
234
235
236
237
# File 'lib/cod/tcp_client.rb', line 227

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.



207
208
209
210
211
212
213
214
# File 'lib/cod/tcp_client.rb', line 207

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.



219
220
221
222
223
# File 'lib/cod/tcp_client.rb', line 219

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