[plt-scheme] tiny server -- recommendations?

From: Ben Simon (ben at amazingmedia.com)
Date: Wed Jan 26 10:54:41 EST 2005

Hey All,

In an attempt to troubleshoot a problem with my network [1], I decided
to write a tiny server implementation.  The server is supposed to look
like an HTTP server, but always return the same response.  Once I have
it working correctly, I hope to add in timing so I can figure out why
I'm getting an unexpected network delay.

The first pass at this server is:

| (define (mini-server port)
|   (define request-id 0)
|   (define sema (make-semaphore 1))
|   (define (log)
|     (semaphore-wait sema)
|     (display (format "req ~a\n" request-id))
|     (set! request-id (add1 request-id))
|     (semaphore-post sema))
|   (define (handle ip op)
|     (define (w line)
|       (display (format "~a\r\n" line) op))
|     (log)
|     (w "HTTP/1.1 200 OK")
|     (w "Content-Type: text/plain")
|     (w "Content-Length: 13")
|     (w "")
|     (w "Hello World"))
|   (display (format "mini-server listening on ~a...\n" port))
|   (let ((listener (tcp-listen port 40 #t #f)))
|     (with-handlers ([exn:break? (lambda (ex)
|                                   (display "shutting down...\n")
|                                   (tcp-close listener))])
|       (let loop ()
|         (let-values ([(ip op) (tcp-accept listener)])
|           (thread (lambda ()
|                     (handle ip op)
|                     (close-input-port ip)
|                     (close-output-port op)))
|           (loop))))))

I can run this by doing:
  (mini-server 8080)

Using apache's `ab' [2] I can do:
   ab -n 1 http://localhost:8080/foo.txt
and I get back timing information.

However, when I do:
   ab -n 2 http://localhost:8080/foo.txt   [3]
the process just hangs. 

What's strange is that the mini-server notices and responds to both
requests, but `ab' never exits.

My guess is that I'm missing something obvious about how I should be
closing connections or some other detail.

In general, I'm curious if I'm even using the right idiom to write this

Thanks for suggestions of any improvements I can make.


[1] Running on: Linux 2.4.20, mzscheme 207 

[2] ab makes a request to the provided URL and times it.

[3] ab -n 2 says to run two requests in sequential order

Posted on the users mailing list.