|
| 1 | +#!/usr/bin/env ruby |
| 2 | +# frozen_string_literal: true |
| 3 | + |
| 4 | +# Released under the MIT License. |
| 5 | +# Copyright, 2024, by Samuel Williams. |
| 6 | + |
| 7 | +require 'async' |
| 8 | +require 'async/http/client' |
| 9 | +require 'async/http/server' |
| 10 | +require 'async/http/endpoint' |
| 11 | + |
| 12 | +require 'protocol/http/body/streamable' |
| 13 | +require 'protocol/http/body/writable' |
| 14 | +require 'protocol/http/body/stream' |
| 15 | + |
| 16 | +endpoint = Async::HTTP::Endpoint.parse('http://localhost:3000') |
| 17 | + |
| 18 | +Async do |
| 19 | + server = Async::HTTP::Server.for(endpoint) do |request| |
| 20 | + output = Protocol::HTTP::Body::Streamable.response(request) do |stream| |
| 21 | + $stderr.puts "Server writing chunks..." |
| 22 | + stream.write("Hello, ") |
| 23 | + stream.write("World!") |
| 24 | + |
| 25 | + $stderr.puts "Server reading chunks..." |
| 26 | + while chunk = stream.readpartial(1024) |
| 27 | + puts chunk |
| 28 | + end |
| 29 | + rescue EOFError |
| 30 | + $stderr.puts "Server EOF." |
| 31 | + # Ignore EOF errors. |
| 32 | + ensure |
| 33 | + $stderr.puts "Server closing stream." |
| 34 | + stream.close |
| 35 | + end |
| 36 | + |
| 37 | + Protocol::HTTP::Response[200, {}, output] |
| 38 | + end |
| 39 | + |
| 40 | + server_task = Async{server.run} |
| 41 | + |
| 42 | + client = Async::HTTP::Client.new(endpoint) |
| 43 | + |
| 44 | + streamable = Protocol::HTTP::Body::Streamable.request do |stream| |
| 45 | + # Simple echo client: |
| 46 | + while chunk = stream.readpartial(1024) |
| 47 | + $stderr.puts "Client chunk: #{chunk.inspect}" |
| 48 | + stream.write(chunk) |
| 49 | + $stderr.puts "Client waiting for next chunk..." |
| 50 | + end |
| 51 | + rescue EOFError |
| 52 | + $stderr.puts "Client EOF." |
| 53 | + # Ignore EOF errors. |
| 54 | + ensure |
| 55 | + $stderr.puts "Client closing stream." |
| 56 | + stream.close |
| 57 | + end |
| 58 | + |
| 59 | + $stderr.puts "Client sending request..." |
| 60 | + response = client.get("/", body: streamable) |
| 61 | + $stderr.puts "Client received response and streaming it..." |
| 62 | + streamable.stream(response.body) |
| 63 | + $stderr.puts "Client done streaming response." |
| 64 | +ensure |
| 65 | + server_task.stop |
| 66 | +end |
0 commit comments