Stream ajax events, how do I handle long persistent connections?

Hi guys,

To get familiar with nginx’s module api, I wrote a quick and
dirty handler module that for now simply spits out a text/html
based on the uri.

Now, to go one step further, I want to send to the client a
series of strings with delays in between them.
(My intermediate goal is to implement something like:
http://ajaxify.com/run/streaming/ — basically print out
javascript on certain events and client updates some div…
nothing fancy.)

To get things started I just want to print “hello1” … “hello50”
with 1 second delays in between.

Obviously, if I just loop inside my handler callback with calls
to sleep in between the ngx_http_output_filter calls,
it works, but the worker process won’t accept any other clients
while it’s in the loop… I don’t expect more than 30 simult
clients/conns but don’t think having 30 worker processes is the
answer :stuck_out_tongue:

What is the proper way to do this? Should I spawn a separate
thread inside the handler? (but then how do I coordinate the life
cycle of the connection/request? seems pretty dangerous and
locking this and that appears hairy)

Is there some way to return from the handler with a flag saying
“there’s more data, so call me again with the same request context”?

I’m also looking at the upstream type module api, it seems very
interesting and I might be able to hook into that instead?
I suppose I can write a separate standalone process and hook w/ fastcgi
but I want see if I can have everything inside the module.

I’m still studying the source for clues…
would appreciate any hints. TIA

-Emit.

Obviously, if I just loop inside my handler callback with calls
to sleep in between the ngx_http_output_filter calls,
it works, but the worker process won’t accept any other clients
while it’s in the loop… I don’t expect more than 30 simult
clients/conns but don’t think having 30 worker processes is the
answer :stuck_out_tongue:

What is the proper way to do this?

You probably want to setup a timer. You do that by creating an object
of type ngx_event_t. You probably will need to set at least the
handler, log, and data fields.

The handler is a callback of type

void (*handler)(ngx_event_t *ev)

To start the timer use

void ngx_add_timer(ngx_event_t *ev, ngx_msec_t timer);

To stop it use

void ngx_del_timer(ngx_event_t *ev);

Then you can check if the timer is activated by looking at
ev->timer_set.