#!/usr/bin/env scheme-chicken
;;;; tcp-server.scm -*- Scheme -*-
;
; A simple TCP server. Runs endlessly and listens for connections on port 4242.
; Connecting processes are required to guess a number between 1 and 10.
; 
; - Usage: tcp-server.scm
;
;      or: csi tcp-server.scm -eval "(main)"


(define listener (tcp-listen 4242))

(randomize)

(define (main . _)
  (print "TCP-SERVER: server started. Listening...")
  (let loop ()
    (let-values ([(in out) (tcp-accept listener)])
      (let-values ([(me you) (tcp-addresses in)])
	(print "TCP-SERVER: connected with " you)
	(let ([num (add1 (random 10))])
	  (write-line (format "Hello ~A, I'm ~A. please guess a number between 1 and 10." you me) out)
	  (let loop ([tries 1])
	    (let* ([try (read in)]
		   [ok (equal? try num)] )
	      (format #t "TCP-SERVER: ~A guessed ~A (try ~A) - ~A~%" you try tries (if ok "right" "wrong"))
	      (if (equal? try num)
		  (write-line "That's right!" out)
		  (begin
		    (write-line "That's wrong." out)
		    (loop (add1 tries)) ) ) ) ) )
	(print "TCP-SERVER: closing connection with " you)
	(close-input-port in)
	(close-output-port out) ) )
    (loop) ) )
