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:



119
120
121
122
# File 'lib/cod/tcp_client.rb', line 119

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

Instance Attribute Details

#destinationObject (readonly)

Returns the value of attribute destination.



124
125
126
# File 'lib/cod/tcp_client.rb', line 124

def destination
  @destination
end

#socketObject (readonly)

Returns the value of attribute socket.



125
126
127
# File 'lib/cod/tcp_client.rb', line 125

def socket
  @socket
end

Instance Method Details

#closeObject

Closes the connection and stops reconnection.



170
171
172
173
# File 'lib/cod/tcp_client.rb', line 170

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

#established?Boolean

Returns true if a connection is currently running.

Returns:

  • (Boolean)


129
130
131
# File 'lib/cod/tcp_client.rb', line 129

def established?
  !! @socket
end

#read(serializer) ⇒ Object

Reads one message from the socket if possible.



156
157
158
159
160
161
162
163
164
165
166
# File 'lib/cod/tcp_client.rb', line 156

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.



136
137
138
139
140
141
142
143
# File 'lib/cod/tcp_client.rb', line 136

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.



148
149
150
151
152
# File 'lib/cod/tcp_client.rb', line 148

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