#!/usr/bin/env scheme-chicken
;;;; tcp-client.scm -*- Scheme -*-
;
; A simple TCP client. Connects to port 4242 at a given host (default: localhost)
; and tries to guess a number between 1 and 10.
; 
; - Usage: tcp-client.scm [HOSTNAME]
;
;      or: csi tcp-client.scm -eval "(main '(#f \"HOSTNAME\"))"


(randomize)

(define (main args)
  (let ([host (match args [(_) "localhost"] [(_ host . _) host])]
	[in #f]
	[out #f] )
    (print "TCP-CLIENT: client started. Connecting to " host "...")
    (handle-exceptions ex
	(begin
	  (print "TCP-CLIENT: could not connect to " host ".")
	  (exit) )
      (set!-values (in out) (tcp-connect host 4242)) )
    (let-values ([(me you) (tcp-addresses in)])
      (print "TCP-CLIENT: [SERVER " you "] " (read-line in))
      (let loop ()
	(let ([num (add1 (random 10))])
	  (print "TCP-CLIENT: guessing " num)
	  (format out "~A~%" num)
	  (let ([reply (read-line in)])
	    (unless (eof-object? reply)
	      (if (string-search "right" reply)
		  (print "TCP-CLIENT: I did it!")
		  (loop) ) ) ) ) )
      (print "TCP-CLIENT: connection closed.")
      (close-input-port in)
      (close-output-port out) ) ) )
