zhaojh329 / libuhttpd

A very flexible, lightweight and high performance HTTP server library based on libev and http-parser for Embedded Linux.
MIT License
386 stars 67 forks source link

A question about chunking #4

Closed Hermanverschooten closed 4 years ago

Hermanverschooten commented 5 years ago

Hi, I thought that by chunking I would be able to like stream the output to a webpage, but it doesn't work. The browser waits and then gets it al at once. I do

conn->send_head(conn, 200, -1, NULL);
conn->chunk_printf(conn, render_header());
conn->chunk_printf(conn, "In progress...");
sleep(3); // symbolizing the work
conn->chunk_printf(conn,"Complete");
conn->chunk_printf(conn, render_footer());
conn->chunk_end(conn);

So I would expect to have the header and the In progress... on screen, and after 3 seconds the rest. But my browser just waits the 3 seconds and then shows it all. The same happens when I do it with curl.

What am I doing wrong?

Thanks,

Herman

zhaojh329 commented 5 years ago

Here, the data is only put into buf, and no real sending operation is performed. The real sending operation will be performed only after the on_request function returns.

zhaojh329 commented 5 years ago
static void delay_send(struct ev_loop *loop, struct ev_timer *w, int revents)
{
    struct uh_connection *conn = (struct uh_connection *)w->data;
    conn->chunk_printf(conn,"Complete");
    conn->chunk_printf(conn, render_footer());
    conn->chunk_end(conn);
    free(w);
}

static void on_request(struct uh_connection *conn)
{
    struct ev_timer *timer;

    conn->send_head(conn, 200, -1, NULL);
    conn->chunk_printf(conn, render_header());
    conn->chunk_printf(conn, "In progress...");

    timer = malloc(sizeof(struct ev_timer));
    ev_timer_init(timer, delay_send, 3.0, 0.0);
    timer->data = conn;
    ev_timer_start(conn->srv->loop, timer);
}
Hermanverschooten commented 5 years ago

Oh, I see. How would you go about making a call to a function without a delay. I am writing something on the page, doing a web-request and updating the page with the result.