syndicate-rkt/syndicate/examples/server-chat-client.rkt

42 lines
1.7 KiB
Racket

#lang imperative-syndicate
(require/activate imperative-syndicate/distributed)
(require/activate imperative-syndicate/drivers/external-event)
(require (only-in racket/port read-line-evt))
(assertion-struct Present (name))
(message-struct Says (who what))
(define host (make-parameter "localhost"))
(define port (make-parameter 8001))
(define scope (make-parameter "chat"))
(module+ main
(require racket/cmdline)
(command-line #:once-each
["--host" hostname "Server hostname" (host hostname)]
["--port" portnum "Server port number" (port (string->number portnum))]
["--scope" scopename "Server scope" (scope scopename)]))
(spawn #:name 'main
(field [username (symbol->string (strong-gensym 'chatter-))])
(define root-facet (current-facet))
(define url (server-tcp-connection (host) (port) (scope)))
(during (server-connected url)
(on-start (log-info "Connected to server."))
(on-stop (log-info "Disconnected from server."))
(on (asserted (from-server url (Present $who))) (printf "~a arrived.\n" who))
(on (retracted (from-server url (Present $who))) (printf "~a departed.\n" who))
(on (message (from-server url (Says $who $what))) (printf "~a: ~a\n" who what))
(assert (to-server url (Present (username))))
(define stdin-evt (read-line-evt (current-input-port) 'any))
(on (message (inbound (external-event stdin-evt (list $line))))
(match line
[(? eof-object?) (stop-facet root-facet)]
[(pregexp #px"^/nick (.+)$" (list _ newnick)) (username newnick)]
[other (send! (to-server url (Says (username) other)))]))))