The :stream_bidi
plugin builds on top of the :stream
plugin functionality to deliver an API supporting HTTP/2 bidirectional streaming, where a request and a response send and receive data interchangeably.
Below is an example of how to use HTTP/2 streaming to send a ping and get a pong 5 times before terminating the stream.
session = HTTPX.plugin(:stream_bidi)
request = session.build_request(
"POST",
"https://your-origin.com/stream",
headers: { "content-type" => "application/x-ndjson" },
body: ["{\"message\":\"started\"}\n"]
)
chunks = []
response = session.request(request, stream: true)
# consume response stream just like with the `:stream` plugin
response.each.each_with_index do |chunk, idx| # rubocop:disable Style/RedundantEach
if idx < 4
request << "{\"message\":\"pong\"}\n"
else
request.close
end
chunks << chunk
end
Next: Custom Plugins