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 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
|
#!/usr/bin/env ruby
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2024, by Samuel Williams.
require "async"
require "async/http/client"
require "async/http/server"
require "async/http/endpoint"
require "protocol/http/body/stream"
require "protocol/http/body/writable"
def make_server(endpoint)
Async::HTTP::Server.for(endpoint) do |request|
output = Protocol::HTTP::Body::Writable.new
stream = Protocol::HTTP::Body::Stream.new(request.body, output)
Async do
stream.write("Hello, ")
stream.write("World!")
stream.close_write
# Simple echo server:
$stderr.puts "Server reading chunks..."
while chunk = stream.readpartial(1024)
puts chunk
end
rescue EOFError
# Ignore EOF errors.
ensure
stream.close
end
Protocol::HTTP::Response[200, {}, output]
end
end
Async do |task|
endpoint = Async::HTTP::Endpoint.parse("http://localhost:3000")
server_task = task.async{make_server(endpoint).run}
client = Async::HTTP::Client.new(endpoint)
input = Protocol::HTTP::Body::Writable.new
response = client.get("/", body: input)
begin
stream = Protocol::HTTP::Body::Stream.new(response.body, input)
$stderr.puts "Client echoing chunks..."
while chunk = stream.readpartial(1024)
stream.write(chunk)
end
rescue EOFError
# Ignore EOF errors.
ensure
stream.close
end
ensure
server_task.stop
end
|