From 5f70a85f7e77d43aad2ac8ac79cc7269fe092935 Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Thu, 5 Sep 2024 23:08:53 -0500 Subject: [PATCH] Add chat server example. --- examples/chatserver.janet | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 examples/chatserver.janet diff --git a/examples/chatserver.janet b/examples/chatserver.janet new file mode 100644 index 00000000..11bce077 --- /dev/null +++ b/examples/chatserver.janet @@ -0,0 +1,35 @@ +(def conmap @{}) + +(defn broadcast [em msg] + (eachk par conmap + (if (not= par em) + (if-let [tar (get conmap par)] + (net/write tar (string/format "[%s]:%s" em msg)))))) + +(defn handler + [connection] + (print "created " connection) + (net/write connection "Whats your name?\n") + (def name (string/trim (string (ev/read connection 100)))) + (print name " connected") + (if (get conmap name) + (do + (net/write connection "Name already taken!") + (:close connection)) + (do + (put conmap name connection) + (net/write connection (string/format "Welcome %s\n" name)) + (defer (do + (put conmap name nil) + (:close connection)) + (while (def msg (ev/read connection 100)) + (broadcast name (string msg))) + (print name " disconnected"))))) + +(defn main [& args] + (printf "STARTING SERVER...") + (flush) + (def my-server (net/listen "127.0.0.1" "8000")) + (forever + (def connection (net/accept my-server)) + (ev/call handler connection)))