Class: Fastdfs::Client::Socket

Inherits:
Object
  • Object
show all
Defined in:
lib/fastdfs-client/socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, options = {}) ⇒ Socket



12
13
14
15
16
17
18
19
20
# File 'lib/fastdfs-client/socket.rb', line 12

def initialize(host, port, options = {})
  @host = host
  @port = port
  connection
  @header_len = ProtoCommon::HEAD_LEN
  @options = options || {}
  @connection_timeout = @options[:connection_timeout] || 3
  @recv_timeout = @options[:recv_timeout] || 3
end

Instance Attribute Details

#cmdObject

Returns the value of attribute cmd.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def cmd
  @cmd
end

#contentObject

Returns the value of attribute content.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def content
  @content
end

#headerObject

Returns the value of attribute header.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def header
  @header
end

#header_lenObject

Returns the value of attribute header_len.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def header_len
  @header_len
end

#hostObject

Returns the value of attribute host.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def host
  @host
end

#portObject

Returns the value of attribute port.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def port
  @port
end

#socketObject

Returns the value of attribute socket.



10
11
12
# File 'lib/fastdfs-client/socket.rb', line 10

def socket
  @socket
end

Instance Method Details

#closeObject



29
30
31
# File 'lib/fastdfs-client/socket.rb', line 29

def close 
  @socket.close if connected
end

#connectedObject



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

def connected
  !@socket.closed?
end

#connectionObject



33
34
35
36
37
38
39
# File 'lib/fastdfs-client/socket.rb', line 33

def connection
  if @socket.nil? || !connected
    Timeout.timeout(@connection_timeout) do
      @socket = TCPSocket.new(@host, @port)  
    end
  end
end

#receive {|@content| ... } ⇒ Object

Yields:



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/fastdfs-client/socket.rb', line 45

def receive
  @content = nil
  Timeout.timeout(@recv_timeout) do 
    @header = @socket.recv(@header_len).unpack("C*")
  end
  res_header = parseHeader
  if res_header[:body_length] > 0
    Timeout.timeout(@recv_timeout) do 
      @content = @socket.recv(@header.to_pack_long) 
    end
  end
  yield @content if block_given?
end

#write(*args) ⇒ Object



22
23
24
25
26
27
# File 'lib/fastdfs-client/socket.rb', line 22

def write(*args)
  @cmd = args.shift
  pkg = args.shift
  pkg = pkg.pack("C*") if pkg.is_a?(Array)
  @socket.write pkg
end