Skip to content

Instantly share code, notes, and snippets.

Created November 22, 2020 22:42
What would you like to do?
Janet RPC Example
(import spork/rpc)
(def c (rpc/client "" "9001" "joe"))
# Will print on server
(:print c "Hello world!")
(:add c 1 3 5 7 9) # -> 25
(pp (:add c 1 3 5 7 9))
(let [fiber (:fiber c)]
(for i 0 5
(print (resume fiber))))
# Bi-directional data flow with fibers over RPC
(def f (fiber/new (fn []
(for i 0 5
(yield i)))))
(let [bidi (:bidi c f)
arr @[]]
(while true
(try # we can't see if the fiber f is dead because the rpc server is consuming it not the client.
(let [v (resume bidi)]
(if v # v is nil if fiber is dead and we don't want that.
(array/push arr v)))
([err] (do
(pp arr)
(let [file (:file/open c "./foo.txt")]
(pp (:file/read c file :all)))
(let [file (:file/open c "./foo.txt")
to (file/open "./bar.txt" :a)]
(while true
(let [line (:file/read c file :line)]
(if line
(file/write to line)
(file/close to)
(print (file/read (file/open "./bar.txt") :all)))
# Close the underlying connection
(:close c)
(declare-project :name "rpc"
:description "RPC test."
:dependencies [""])
(import spork/rpc)
(defn fiber [self]
(fiber/new (fn []
(for i 0 5
(yield i)))))
(defn bidi [self rfiber]
(fiber/new (fn []
(while true
(yield (inc (resume rfiber)))))))
(def handles @{})
(defn- make-handle []
(string/join (map | (string/format "%02x" $) (os/cryptorand 12))))
(defn open [self file & mode]
(let [handle (make-handle)]
(put handles handle (file/open file))
(defn read [self handle what]
(file/read (handles handle) what))
(def functions
@{:print (fn [self x] (print x))
:add (fn [self & xs] (sum xs))
:fiber fiber
:bidi bidi
:file/open open
:file/read read})
(rpc/server functions "" "9001")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment