examples/chat.ss
#lang scheme
(require srfi/31 "../main.ss")

(define (start-chat [port 1234] . listen-args)
  (define listener (apply ws-listen port listen-args))
  (define connections '())
  
  (define accepter
    (thread
     (rec (loop)
       (set! connections (cons (ws-accept listener) connections))
       (loop))))
  
  (define distributor
    (thread
     (rec (loop)
       (cond
         [(apply
           sync
           (wrap-evt (alarm-evt (+ (current-inexact-milliseconds) 3000)) (λ (evt) #f))
           (map ws-receive-ready-evt connections))
          => (λ (ready)
               (let ([frame (ws-receive ready)])
                 (for ([socket (in-list connections)] #:when (not (eq? socket ready)))
                   (ws-send socket frame))))])
       (loop))))
  
  (define (done!)
    (kill-thread accepter)
    (kill-thread distributor)
    (ws-close listener)
    (for-each ws-close connections))
  
  done!)

(provide start-chat)