Class: TCPClient

Inherits:
Object
  • Object
show all
Defined in:
lib/tcp-client.rb,
lib/tcp-client/address.rb,
lib/tcp-client/version.rb,
lib/tcp-client/ssl_socket.rb,
lib/tcp-client/tcp_socket.rb,
lib/tcp-client/configuration.rb

Defined Under Namespace

Classes: Address, Configuration, NoOpenSSL, NotConnected

Constant Summary collapse

Timeout =
Class.new(IOError)
VERSION =
'0.0.6'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTCPClient

Returns a new instance of TCPClient.



37
38
39
# File 'lib/tcp-client.rb', line 37

def initialize
  @socket = @address = @write_timeout = @read_timeout = nil
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address.



35
36
37
# File 'lib/tcp-client.rb', line 35

def address
  @address
end

Class Method Details

.open(addr, configuration = Configuration.new) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/tcp-client.rb', line 24

def self.open(addr, configuration = Configuration.new)
  addr = Address.new(addr)
  client = new
  client.connect(addr, configuration)
  return yield(client) if block_given?
  client, ret = nil, client
  ret
ensure
  client.close if client
end

Instance Method Details

#closeObject



56
57
58
59
60
61
62
# File 'lib/tcp-client.rb', line 56

def close
  socket, @socket = @socket, nil
  socket.close if socket
  self
rescue IOError
  self
end

#closed?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/tcp-client.rb', line 64

def closed?
  @socket.nil? || @socket.closed?
end

#connect(addr, configuration) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/tcp-client.rb', line 45

def connect(addr, configuration)
  close
  NoOpenSSL.raise! if configuration.ssl? && !defined?(SSLSocket)
  @address = Address.new(addr)
  @socket = TCPSocket.new(@address, configuration, Timeout)
  @socket = SSLSocket.new(@socket, @address, configuration, Timeout) if configuration.ssl?
  @write_timeout = configuration.write_timeout
  @read_timeout = configuration.read_timeout
  self
end

#flushObject



76
77
78
79
# File 'lib/tcp-client.rb', line 76

def flush
  @socket.flush unless closed?
  self
end

#read(nbytes, timeout: @read_timeout) ⇒ Object



68
69
70
# File 'lib/tcp-client.rb', line 68

def read(nbytes, timeout: @read_timeout)
  closed? ? NotConnected.raise!(self) : @socket.read(nbytes, timeout: timeout, exception: Timeout)
end

#to_sObject



41
42
43
# File 'lib/tcp-client.rb', line 41

def to_s
  @address ? @address.to_s : ''
end

#write(*msg, timeout: @write_timeout) ⇒ Object



72
73
74
# File 'lib/tcp-client.rb', line 72

def write(*msg, timeout: @write_timeout)
  closed? ? NotConnected.raise!(self) : @socket.write(*msg, timeout: timeout, exception: Timeout)
end