no title added by buhman on Sun Dec 2 21:30:09 2018

(use tcp6
     srfi-18
     matchable)

(define (chat-message text port)
  (let ((msg (list 'event 'chat-message text)))
    (write msg port)))

(define (input-loop out)
  (let loop ()
    (let ((line (read-line)))
      (when (not (eq? line #!eof))
        (chat-message line out)
        (thread-yield!)
        (loop)))))

(define +hostname+ "localhost")
(define +port+ 4242)

(define (dispatch-message msg)
  (match msg
    (`(event . ,evt)
     (print "evt:" evt)
     (flush-output))))

(define (handle-message in)
  (let ((msg (read in)))
    (case msg
      ((#!eof) #f)
      (else
       (dispatch-message msg)
       #t))))

(define (client-loop in)
  (let handle-next-message ()
    (print "handling")
    (when (and (not (port-closed? in))
               (handle-message in))
      (thread-yield!)
      (handle-next-message))))

(define (start-client)
  (let-values (((in out) (tcp-connect +hostname+ +port+)))
    (let ((client (thread-start! (lambda () (client-loop in))))
          (input (thread-start! (lambda () (input-loop out)))))
      (thread-join! client)
      (thread-join! input))))

(start-client)