(in-package "PORT")

;;; ----------------------------------------------------------------------
;;; A KPML Mini-Client from Lisp that shows how a simple Lisp server
;;; using the CLOCC portable port package can support a generation
;;; server. The server is in kpml-mini-server.lisp
;;;
;;; To use this, the port facilities must have been loaded first!
;;; Code adapted from http://cl-cookbook.sourceforce.net/sockets.html
;;;
;;; To use: send an SPL to the server (you must know which port and host)
;;; the server is running on) with the function call:
;;;         (port::generate <server> <port-number> <spl>)
;;;
;;; <spl> should be a list containing a control word as first element,
;;,       either :gen for generate from the logical-form that follows,
;;;       or something else that gets defined sometime...
;;;
;;; ----------------------------------------------------------------------

   ;;; Utility...

(defun send-lisp-line (stream line)
  "Send a line of text to the HTTP stream, terminating it with CR+LF."
  (print line stream)
  (princ #\Return stream)
  (princ #\Newline stream))

(defun GENERATE (server port spl)
  "Send a request for generation of an spl `spl' to a KPML server on host
   `server', port number `port'. Print the generated results
   to standard output and return as result of function."
  ;; Open connection
  (let ((socket (open-socket server port))
	(lines nil))
    (unless (streamp socket) (format t "~% No server!") (return-from GENERATE :no-server))
    (unwind-protect
	(progn
	  (format t "> Sending request to ~a:~a...~%" server port)
	  ;; Send request
	  (send-lisp-line socket spl)
	  (force-output socket)
             
	  ;; Read response and output it
	  (format t "> Received response:~%")
	  (loop
	   (let ((line (read-line socket nil nil)))
	     (unless line (return))
	     (push line lines)
	     (format t "~a~%" line))))
         
      ;; Close socket before exiting.
      (close socket))
    (reverse lines)))

(format t "~2%... READY, send generation requests with~%    (port::generate <server> <port-number> '(:gen <spl>))")
