From 4c26fd8e0c8bde6bac5a649629c79a6db82cd06f Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Fri, 6 Nov 2015 10:21:26 +0900 Subject: client: constructor accept IO object --- lib/plum/client.rb | 42 ++++++++++++++++++++++++++---------------- lib/plum/client/connection.rb | 1 - 2 files changed, 26 insertions(+), 17 deletions(-) (limited to 'lib') diff --git a/lib/plum/client.rb b/lib/plum/client.rb index 81066d7..35c4001 100644 --- a/lib/plum/client.rb +++ b/lib/plum/client.rb @@ -2,8 +2,9 @@ module Plum class Client DEFAULT_CONFIG = { - https: true, - verify_mode: OpenSSL::SSL::VERIFY_NONE, + tls: true, + scheme: "https", + verify_mode: OpenSSL::SSL::VERIFY_PEER, }.freeze attr_reader :host, :port, :config @@ -11,20 +12,26 @@ module Plum # Creates a new HTTP client and starts communication. # A shorthand for `Plum::Client.new(args).start(&block)` - def self.start(host, port, config = {}, &block) + def self.start(host, port = nil, config = {}, &block) client = self.new(host, port, config) client.start(&block) end - # @param host [String] the host to connect + # Creates a new HTTP client. + # @param host [String | IO] the host to connect, or IO object. # @param port [Integer] the port number to connect # @param config [Hash] the client configuration - def initialize(host, port, config = {}) - @host = host - @port = port + def initialize(host, port = nil, config = {}) + if host.is_a?(IO) + @socket = host + else + @host = host + @port = port || (config[:tls] ? 443 : 80) + end @config = DEFAULT_CONFIG.merge(config) @response_handlers = {} @responses = {} + @started = false end # Starts communication. @@ -99,7 +106,7 @@ module Plum base_headers = { ":method" => nil, ":path" => nil, ":authority" => (@config[:hostname] || @host), - ":scheme" => @config[:https] ? "https" : "http" } + ":scheme" => (@config[:scheme] || "https") } response = request_async(base_headers.merge(headers), body) wait(response) @@ -154,16 +161,19 @@ module Plum private def _start @started = true - sock = TCPSocket.open(host, port) - if config[:https] - ctx = @config[:ssl_context] || new_ssl_ctx - sock = OpenSSL::SSL::SSLSocket.new(sock, ctx) - sock.sync_close = true - sock.connect + unless @socket + sock = TCPSocket.open(host, port) + if config[:tls] + ctx = @config[:ssl_context] || new_ssl_ctx + sock = OpenSSL::SSL::SSLSocket.new(sock, ctx) + sock.sync_close = true + sock.connect + end + + @socket = sock end - @socket = sock - @plum = setup_plum(sock) + @plum = setup_plum(@socket) end def setup_plum(sock) diff --git a/lib/plum/client/connection.rb b/lib/plum/client/connection.rb index 8721fb5..26e53b3 100644 --- a/lib/plum/client/connection.rb +++ b/lib/plum/client/connection.rb @@ -11,7 +11,6 @@ module Plum end # Create a new stream for HTTP request. - # @param args [Hash] the argument for Stream.new def open_stream next_id = @max_stream_id + (@max_stream_id.even? ? 1 : 2) stream(next_id) -- cgit v1.2.3