Class: Mongo::TCPSocket

Inherits:
Object show all
Defined in:
lib/mongo/util/tcp_socket.rb

Overview

Wrapper class for Socket

Emulates TCPSocket with operation and connection timeout sans Timeout::timeout

Direct Known Subclasses

UNIXSocket

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, op_timeout = nil, connect_timeout = nil) ⇒ TCPSocket

Returns a new instance of TCPSocket.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mongo/util/tcp_socket.rb', line 13

def initialize(host, port, op_timeout=nil, connect_timeout=nil)
  @op_timeout = op_timeout
  @connect_timeout = connect_timeout
  @pid = Process.pid

  # TODO: Prefer ipv6 if server is ipv6 enabled
  @address = Socket.getaddrinfo(host, nil, Socket::AF_INET).first[3]
  @port = port

  @socket_address = Socket.pack_sockaddr_in(@port, @address)
  @socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
  @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)

  connect
end

Instance Attribute Details

#pidObject

Returns the value of attribute pid.



11
12
13
# File 'lib/mongo/util/tcp_socket.rb', line 11

def pid
  @pid
end

#poolObject

Returns the value of attribute pool.



11
12
13
# File 'lib/mongo/util/tcp_socket.rb', line 11

def pool
  @pool
end

Instance Method Details

#closeObject



62
63
64
# File 'lib/mongo/util/tcp_socket.rb', line 62

def close
  @socket.close
end

#closed?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/mongo/util/tcp_socket.rb', line 66

def closed?
  @socket.closed?
end

#connectObject



29
30
31
32
33
34
35
36
37
# File 'lib/mongo/util/tcp_socket.rb', line 29

def connect
  if @connect_timeout
    Timeout::timeout(@connect_timeout, OperationTimeout) do
      @socket.connect(@socket_address)
    end
  else
    @socket.connect(@socket_address)
  end
end

#read(maxlen, buffer) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/mongo/util/tcp_socket.rb', line 43

def read(maxlen, buffer)
  # Block on data to read for @op_timeout seconds
  begin
    ready = IO.select([@socket], nil, [@socket], @op_timeout)
    unless ready
      raise OperationTimeout
    end
  rescue IOError
    raise ConnectionFailure
  end

  # Read data from socket
  begin
    @socket.sysread(maxlen, buffer)
  rescue SystemCallError, IOError => ex
    raise ConnectionFailure, ex
  end
end

#send(data) ⇒ Object



39
40
41
# File 'lib/mongo/util/tcp_socket.rb', line 39

def send(data)
  @socket.write(data)
end