Stuck at a first hurdle


For my own personal reasons I'd like to find my way around this new (to me) language. I'd like to learn how to do a fairly trivial task, a small web service (preferably in FCGI) that streams output, one line per second to a client. This should result in "chunked" encoding as it could run for hours, but the client will just get a line showing how many seconds they've been connected.

I appreciate that most people would think this is a silly task, but trust me, I do have my reasons!

So far, I've tried to understand how to use "Iron", "Rocket", and "hyper", but they all seem to focus on delivering a single response, and not a response that sends staged output.

Can anyone point me at simple instructions please?

I'm not too familiar with iron or rocket, so I will outline how to do it with hyper: It's true that hyper requires you to supply the response as a single object, namely a Body, however this is merely a wrapper around what we in the async world call a stream, and asking the stream for its next chunk does not require that chunk to be immediately ready.

One way to do this in the hyper world would be to create your body using the Body::channel function, which gives you a sender and a body. You can provide this body as the body of your response before you have written every chunk to the sender.

For example you might do this:

use tokio::time::{Duration, delay_for};
use bytes::Bytes;

fn create_response() -> Body {
    let (mut send, body) = Body::channel();
    tokio::spawn(async move {
        for _ in 0..10 {
            send.send_data(Bytes::from("This is a line.\n")).await.unwrap();
        // send goes out of scope here
    // return the body

This will spawn a Tokio task which sends another chunk of data every second, however the body can immediately be used as a response. When send goes out of scope, the destructor of the sender will inform the body that no more chunks of data will arrive, and the response is finalized by hyper.


It's taken me a long time to get there, but I think I understand some of this now. Many thanks for helping me get there.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.