#lang imperative-syndicate

(require/activate imperative-syndicate/drivers/tcp)
(require/activate imperative-syndicate/drivers/external-event)
(require (only-in racket/port read-bytes-line-evt))

(spawn (define id 'chat)

       (assert (tcp-connection id (tcp-address "localhost" 5999)))
       (on (asserted (tcp-accepted id)) (printf "*** Connected.\n"))
       (stop-when (retracted (tcp-accepted id)) (printf "*** Remote EOF. Terminating.\n"))

       (on (message (tcp-in id $bs))
           (write-bytes bs)
           (flush-output))

       (define stdin-evt (read-bytes-line-evt (current-input-port) 'any))
       (on (message (inbound (external-event stdin-evt (list $line))))
           (if (eof-object? line)
               (stop-current-facet (printf "*** Local EOF. Terminating.\n"))
               (send! (tcp-out id (bytes-append line #"\n"))))))
