[Rails] Re: interactive web app

Matthew Palmer
Wed, 05 Jul 2006 22:30:26 -0000

On Wed, Jul 05, 2006 at 03:35:25PM +0200, User wrote:
> I have an arbitrary program written in any language, and it is a binary
> (ie foo.exe), that will print out output to stdout constantly every 3-5
> seconds.
>
> Is there a way that I can have a web application designed in rails that
> will print the output of this program to the browser every 3-5 seconds
> in realtime, preferably even in an ajax manner.

Yes.  <grin>

What you need is to make sure that the producer flushes it''s output
when
it''s finished writing for it''s few seconds (because it
doesn''t become
available for you to read until it''s escaped the producer''s
buffers), and
redirect the producer''s output to a named pipe.

As other posters have said, you use a repeating AJAX call in the browser to
call an action in the webserver, which simply opens the pipe for
non-blocking reads, sucks out all of the available data, and then dumps it
back to the browser.  The AJAX call will probably then append that data to
the end of the current contents of the div (or replace it, or something --
whatever you need your app to do).

The important things to note are:

* Use a named pipe.  If you write to a regular file, you''ll need to
keep
note of where you''re up to in the file, and that''s tricky
unless you use
some seriously creepy shared state (you can''t delete the file because
the producer''s redirection will still point to the old file handle).

* This method will only work for a single consumer.  If you''ve got
multiple
reading it, they''ll each only get some of the output.  You can send the
data
to multiple writers, but you''ll need to maintain shared storage of the
producer''s output and remember where each client is up to in the
stream.
Have fun with *that* one.

* You must use non-blocking reads.  If you open the pipe normally, your
program will hang waiting for more output, which isn''t so useful when
you''ve
got an AJAX call waiting for you.

* All of this is Unix-like OS centric.  If you''re restricted to
Windows,
there''s probably ways of making all this work, but you''re not
going to find
out how from me (because I Don''t Do Windows).

- Matt