-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.rb
40 lines (32 loc) · 969 Bytes
/
server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
require 'http/2'
require 'socket'
# Example H2C web app
# Based on https://github.com/igrigorik/http-2/blob/master/example/server.rb
port = ENV.fetch("PORT")
server = TCPServer.new(port)
loop do
sock = server.accept
conn = HTTP2::Server.new
conn.on(:frame) do |bytes|
sock.is_a?(TCPSocket) ? sock.sendmsg(bytes) : sock.write(bytes)
end
conn.on(:stream) do |stream|
stream.on(:half_close) do
stream.headers({
":status" => "200",
"content-type" => "text/plain"
}, end_stream: false)
stream.data("Hello! This Ruby application is speaking plain text HTTP2 (H2C) with the CF routing layer\n", end_stream: true)
end
end
while !sock.closed? && !(sock.eof? rescue true)
data = sock.readpartial(1024)
begin
conn << data
rescue StandardError => e
puts "#{e.class} exception: #{e.message} - closing socket."
e.backtrace.each { |l| puts "\t" + l }
sock.close
end
end
end