[racket] Implementing long polling ajax

From: Greg Hendershott (greghendershott at gmail.com)
Date: Wed Dec 4 22:58:19 EST 2013

I've done something like this awhile ago, but with a simple web server
more along the lines of what's described in "More: Systems Programming
with Racket" http://docs.racket-lang.org/more/

You accept a TCP connection. You have input and output ports. You read
the HTTP request from the input port. You write a response to the
output port, and call flush-output (important).  And then you... don't
close the output port. You keep it open, and when you have more ready
to write, later, you write it.

Long polling is essentially just keeping the port open a long time (IIUC).

If the _only_ thing your HTTP server will do is this long-polling --
if it's more of a single-purpose web _service_ than serving a whole
web _site_ -- you might consider rolling your own simple server like I
had done using that Racket doc as the starting point.

IIUC Racket's web-server has layers, and the servlet level is
organized around making it easy to handle requests and
immediate/complete responses -- the typical, "not long-polling" case.
Trying to shoe-horn long-polling into that might be awkward, ergo the
continuations and semaphores. Someone like Jay McCarthy could probably
explain how you could hook into Racket's web-server at a simpler
level.  (Which, although simpler, is probably correctly handling a
number of details you'd need to work out if you rolled your own from
scratch.)

For example it _might_ be as simple as using web-server/http --
http://docs.racket-lang.org/web-server/http.html -- and, the
`response` struct's `output` function simply never returns?  It
writes, goes to sleep until you have something more, then writes that,
and so on?  If it turns out to be not quite that simple, hopefully Jay
or someone else can help you out.

Posted on the users mailing list.