class Mongo::TCPSocket

Wrapper class for Socket

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

Public Class Methods

new(host, port, op_timeout=nil, connect_timeout=nil, opts={}) click to toggle source
# File lib/mongo/connection/socket/tcp_socket.rb, line 24
def initialize(host, port, op_timeout=nil, connect_timeout=nil, opts={})
  @op_timeout      = op_timeout
  @connect_timeout = connect_timeout
  @pid             = Process.pid
  @auths           = Set.new

  @socket = handle_connect(host, port)
end

Public Instance Methods

connect(socket, socket_address) click to toggle source
# File lib/mongo/connection/socket/tcp_socket.rb, line 54
def connect(socket, socket_address)
  if @connect_timeout
    Timeout::timeout(@connect_timeout, ConnectionTimeoutError) do
      socket.connect(socket_address)
    end
  else
    socket.connect(socket_address)
  end
end
handle_connect(host, port) click to toggle source
# File lib/mongo/connection/socket/tcp_socket.rb, line 33
def handle_connect(host, port)
  error = nil
  # Following python's lead (see PYTHON-356)
  family = host == 'localhost' ? Socket::AF_INET : Socket::AF_UNSPEC
  addr_info = Socket.getaddrinfo(host, nil, family, Socket::SOCK_STREAM)
  error = nil
  addr_info.each do |info|
    begin
      sock = Socket.new(info[4], Socket::SOCK_STREAM, 0)
      sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
      socket_address = Socket.pack_sockaddr_in(port, info[3])
      connect(sock, socket_address)
      return sock
    rescue IOError, SystemCallError => e
      error = e
      sock.close if sock
    end
  end
  raise error
end
read(maxlen, buffer) click to toggle source
# File lib/mongo/connection/socket/tcp_socket.rb, line 68
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) click to toggle source
# File lib/mongo/connection/socket/tcp_socket.rb, line 64
def send(data)
  @socket.write(data)
end