Class: Stenohttp2::Client::Client

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

Constant Summary collapse

CLIENT_PING_DELAY =
0.1
CLIENT_IDENTIFIER =
'ccxin6f5'

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client

Returns a new instance of Client.



14
15
16
# File 'lib/stenohttp2/client/client.rb', line 14

def initialize(opts = {})
  @server_address = opts.fetch(:server_url)
end

Instance Method Details

#setup_connection_handlersObject

rubocop:enable Metrics/MethodLength, Metrics/AbcSize



69
70
71
72
73
74
75
# File 'lib/stenohttp2/client/client.rb', line 69

def setup_connection_handlers
  conn.on(:frame) do |bytes|
    socket.is_a?(TCPSocket) ? socket.sendmsg(bytes) : socket.write(bytes)
  end

  conn.on(:frame_received) { |frame| ping_handler.handle(frame) }
end

#setup_stream_handlersObject



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/stenohttp2/client/client.rb', line 77

def setup_stream_handlers
  stream.on(:close) do
    log.info 'stream closed'
  end

  stream.on(:headers) do |h|
    log.info "response headers: #{h}"
  end

  stream.on(:data) do |d|
    log.info "response data chunk: <<#{d}>>"
  end
end

#startObject

rubocop:disable Metrics/MethodLength, Metrics/AbcSize



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/stenohttp2/client/client.rb', line 19

def start
  setup_connection_handlers
  setup_stream_handlers
  log.info 'Sending HTTP 2.0 request'

  stream.headers(get_request, end_stream: false) # GET data
  pinger = Thread.new do
    loop do
      conn.ping(SecureRandom.hex(4))
      sleep CLIENT_PING_DELAY
    end
  end

  Thread.kill(pinger)

  ::Stenohttp2::Common::Sender.new(
    message: ::Stenohttp2::Common::Message.new(
      'Witaj świecie. Tajne dane: płatki owsiane, banan, orechy włoskie, jabłko'
    ),
    connection: conn,
    identifier: CLIENT_IDENTIFIER,
    delay: CLIENT_PING_DELAY
  ).call

  pinger = Thread.new do
    loop do
      conn.ping(SecureRandom.hex(4))
      sleep CLIENT_PING_DELAY
    end
  end

  stream.headers(post_request, end_stream: false) # POST data
  stream.data(SecureRandom.hex(20)) # Post some random data to the server

  Thread.kill(pinger)
  while !socket.closed? && !socket.eof?
    data = socket.read_nonblock(1024)
    log.info "Received bytes: #{data.unpack1('H*')}"

    begin
      conn << data
    rescue StandardError => e
      log.info "#{e.class} exception: #{e.message} - closing socket."
      e.backtrace.each { |l| puts "\t#{l}" }
      socket.close
    end
  end
end