#lang racket ;; Only `accept-and-handle' changes, moving the ;; handle work into a thread. (define (serve port-no) (define listener (tcp-listen port-no 5 #t)) (define (loop) (accept-and-handle listener) (loop)) (define t (thread loop)) (lambda () (kill-thread t) (tcp-close listener))) (define (accept-and-handle listener) (define-values (in out) (tcp-accept listener)) (thread (lambda () ;; (sleep (random 10)) ; try uncommenting this (handle in out) (close-input-port in) (close-output-port out)))) (define (handle in out) ;; Discard the request header (up to blank line): (regexp-match #rx"(\r\n|^)\r\n" in) ;; Send reply: (display "HTTP/1.0 200 Okay\r\n" out) (display "Server: k\r\nContent-Type: text/html\r\n\r\n" out) (display "Hello, world!" out))