[racket] web-server and comet-like requests?

From: Danny Yoo (dyoo at cs.wpi.edu)
Date: Mon Feb 21 23:42:47 EST 2011

I'm trying to do a comet-like push for a web-server application.  Say,
for example, that I'm doing something like this:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket

;; Comet demonstration

(require web-server/servlet web-server/servlet-env)

(define ch (make-channel))

(void
 (thread (lambda ()
          (define (start req)
            (cond
              ;; Server-side sync for a program
              [(exists-binding? 'comet (request-bindings req))
               (handle-comet req)]
              [else
               (handle-default req)]))
          (serve/servlet start
                         #:banner? #f
                         #:launch-browser? #f
                         #:quit? #f
                         #:port 8080
                         #:servlet-path "/compile"))))

(define (handle-comet req)
  (let ([v (sync ch)])
    (response/full 200 #"Okay"
                   (current-seconds)
                   #"text/plain; charset=utf-8"
                   empty
                   (list #"" (string->bytes/utf-8 (format "~s" v))))))


(define (handle-default req)
  '(html (body (p "hello world"))))

(define (send-to-client v)
  (channel-put ch v))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Here's the normal order of things:

    1.  I run the above in DrRacket, which starts up the web server.

    2.  I switch to my web browser and visit the page:
http://localhost:8080/compile?comet=t, where the browser waits to get
a response.

    3.  I switch back to DrRacket, and call (send-to-client "hello world").

    4.  Finally, I go back to the web browser, which should
triumphantly show the words "hello world" on screen.

In the normal situation, this seems to work.  The problem, of course,
is what happens when things aren't perfect.  I don't know the
semantics of what web-server will do if the connection drops in the
middle of a sync, as in handle-comet.  What happens?  Do I get a
catchable exception?  This situation is common in Comet applications,
because the connection eventually times out and needs to be
re-established.


Posted on the users mailing list.