;;;;
;;;; socket-client.stk  -- A simple client socket
;;;;
;;;; Copyright © 2003-2020 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
;;;;
;;;;
;;;; This program is free software; you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation; either version 2 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License
;;;; along with this program; if not, write to the Free Software
;;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
;;;; USA.
;;;;
;;;;           Author: Erick Gallesio [eg@essi.fr]
;;;;    Creation date: 27-Jan-2003 22:20 (eg)
;;;;

(define (port-idle-register! port proc)
  (unless (procedure? proc) (error "bad procedure ~S" proc))

  (let ((idle (%port-idle port)))
    (%port-idle port (cons proc idle))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (do-client host port)
  (let* ((p   (make-client-socket host port))
         (in  (socket-input p))
         (out (socket-output p)))
    ;; Create an idle handler which looks at the socket when reading stdin
    (call/ec (lambda (exit)
               (port-idle-register! (current-input-port)
                                    (lambda ()
                                      (when (char-ready? in)
                                        (let ((l (read-line in)))
                                          (if (eof-object? l)
                                              (exit #f)
                                              (format #t "~A\n" l))))))
               ;; Send all read lines on the socket
               (do ((l (read-line) (read-line)))
                   ((eof-object? l))
                 (format out "~A\n" l))))
    (format #t "Exiting client.\n")))


(define (main args)
  (let ((port #f)
        (hostname "localhost"))
    (parse-arguments args
       "Usage: socket-client [options] port"
       "  This program read lines and send them to a given socket"
       "  displaying the response given by the server"
       "Options:"
       (("host" :arg host :alternate "h"  :help "host to connect to [localhost]")
        (set! hostname host))
       (("help" :help "provides help for the command")
        (arg-usage (current-error-port))
        (exit 0))
     (else
       (unless (= (length other-arguments) 1)
         (arg-usage (current-error-port))
         (exit 1))
       (set! port (string->number (car other-arguments)))))

    ;; parameters are parsed. make the client
    (do-client hostname port)))


; LocalWords:  stdin
