Class: HTTPray::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/httpray.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port, timeout = 1, ssl_context = nil) ⇒ Connection

Returns a new instance of Connection.



16
17
18
19
20
21
22
# File 'lib/httpray.rb', line 16

def initialize(host, port, timeout = 1, ssl_context = nil)
  @host = host
  @port = port
  @timeout = timeout
  @ssl_context = ssl_context
  @socket = connect
end

Instance Method Details

#connectObject



93
94
95
96
# File 'lib/httpray.rb', line 93

def connect
  socket, _ = connect2
  socket
end

#connect2Object

private



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/httpray.rb', line 57

def connect2
  address = Socket.getaddrinfo(@host, nil, Socket::AF_INET).first[3]
  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)

  expire_time = Time.now + @timeout
  begin
    raise Timeout if Time.now > expire_time
    socket.connect_nonblock(socket_address)
  rescue IO::WaitReadable, IO::WaitWritable
    select_timeout = expire_time - Time.now
    select_timeout = 0 if select_timeout < 0
    IO.select([socket], [socket], [socket], select_timeout)
    retry
  end

  original_socket = socket
  if @ssl_context
    socket = OpenSSL::SSL::SSLSocket.new(socket, @ssl_context)
    socket.hostname = @host
    socket.sync_close = true
    begin
      raise Timeout if Time.now > expire_time
      socket.connect_nonblock
    rescue IO::WaitReadable, IO::WaitWritable
      select_timeout = expire_time - Time.now
      select_timeout = 0 if select_timeout < 0
      IO.select([socket.io], [socket.io], [socket.io], select_timeout)
      retry
    end
  end
  return socket, original_socket
end

#request(*args) {|socket| ... } ⇒ Object

Yields:



50
51
52
53
# File 'lib/httpray.rb', line 50

def request(*args)
  socket = request!(*args)
  yield(socket) if block_given?
end

#request!(method, uri, headers = {}, body = nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/httpray.rb', line 30

def request!(method, uri, headers = {}, body = nil)
  begin
    IO.select([@socket], [@socket], [@socket], @timeout) if @socket
  rescue; end
  @socket = connect unless @socket && !@socket.closed?
  socket = @socket
  uri = URI.parse(uri) unless URI === uri

  headers = DEFAULT_HEADERS.merge(headers).merge("Host" => uri.host)
  headers["Content-Length"] = body.bytesize if body

  socket.write_nonblock "#{method} #{uri.request_uri} HTTP/1.0\r\n"
  headers.each do |header, value|
    socket.write_nonblock "#{header}: #{value}\r\n"
  end
  socket.write_nonblock "\r\n"
  socket.write_nonblock body if body
  socket
end

#socketObject

public



26
27
28
# File 'lib/httpray.rb', line 26

def socket
  @socket
end