2017-08-10 19:17:28 +00:00
|
|
|
#lang syndicate
|
2017-01-23 21:40:01 +00:00
|
|
|
|
|
|
|
(require syndicate/protocol/advertise)
|
|
|
|
(require/activate syndicate/drivers/tcp)
|
|
|
|
(require (only-in racket/string string-trim))
|
|
|
|
(require racket/format)
|
|
|
|
|
|
|
|
;;---------------------------------------------------------------------------
|
|
|
|
;; Sketch of a translation from the existing TCP protocol into a simpler one
|
|
|
|
|
|
|
|
(struct tcp-connection (id spec) #:prefab)
|
2017-02-10 00:24:02 +00:00
|
|
|
(struct tcp-accepted (id) #:prefab)
|
2017-01-23 21:40:01 +00:00
|
|
|
(struct tcp-out (id text) #:prefab)
|
|
|
|
(struct tcp-in (id text) #:prefab)
|
|
|
|
|
2017-02-15 23:18:19 +00:00
|
|
|
(spawn #:name 'translate-tcp-protocol-into-simpler-sketch
|
|
|
|
(during/spawn (observe (tcp-connection _ $us))
|
2017-01-23 21:40:01 +00:00
|
|
|
(assert (advertise (observe (tcp-channel _ us _))))
|
|
|
|
(on (asserted (advertise (tcp-channel $them us _)))
|
|
|
|
(define id (seal (list them us)))
|
2017-02-15 23:18:19 +00:00
|
|
|
(spawn (stop-when (retracted (advertise (tcp-channel them us _))))
|
2017-02-10 00:24:02 +00:00
|
|
|
(stop-when (retracted (tcp-accepted id)))
|
2017-01-23 21:40:01 +00:00
|
|
|
(assert (tcp-connection id us))
|
|
|
|
(on (message (tcp-channel them us $bs))
|
|
|
|
(send! (tcp-in id (string-trim (bytes->string/utf-8 bs)))))
|
|
|
|
(on (message (tcp-out id $text))
|
|
|
|
(send! (tcp-channel us them (string->bytes/utf-8 (~a text "\n")))))))))
|
|
|
|
|
|
|
|
;;---------------------------------------------------------------------------
|
|
|
|
;; The actual chat part
|
|
|
|
|
|
|
|
(struct speak (who what) #:prefab)
|
|
|
|
(struct present (who) #:prefab)
|
|
|
|
|
2017-02-15 23:18:19 +00:00
|
|
|
(spawn #:name 'chat-server
|
|
|
|
(during/spawn (tcp-connection $id (tcp-listener 5999))
|
2017-02-10 00:24:02 +00:00
|
|
|
(assert (tcp-accepted id))
|
2017-03-14 22:06:02 +00:00
|
|
|
(let ((me (gensym 'user)))
|
|
|
|
(assert (present me))
|
|
|
|
(on (message (tcp-in id $line))
|
|
|
|
(send! (speak me line))))
|
2017-01-23 21:40:01 +00:00
|
|
|
(during (present $user)
|
|
|
|
(on-start (send! (tcp-out id (~a user " arrived"))))
|
2017-03-14 22:06:02 +00:00
|
|
|
(on-stop (send! (tcp-out id (~a user " left"))))
|
|
|
|
(on (message (speak user $text))
|
|
|
|
(send! (tcp-out id (~a user " says '" text "'")))))))
|