Last active
September 26, 2021 21:06
-
-
Save duanebester/97b111a1873047840a43132768f029ce to your computer and use it in GitHub Desktop.
Building a Byte Buffer SocketChannel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn- init-buffer-socket [client] | |
(let [in-ch (async/chan) | |
out-ch (async/chan) | |
header-buf (ByteBuffer/allocate 5) | |
buff-sock (map->ByteBufferSocket {:client client | |
:in in-ch | |
:out out-ch})] | |
;; Read Backend Messages from Postgres | |
(async/go-loop [] | |
(when (connected? client) | |
(let [n (.read client header-buf)] ;; Read header | |
(when (<= 5 n) | |
(let [[tag len] (parse-header header-buf)] | |
(when (pos? len) | |
(let [bb (read-message tag len client)] | |
(.clear header-buf) | |
(when (async/>! in-ch bb) ;; Send to downstream listeners | |
(recur))))))))) | |
;; Send Byte Buffers to Postgres | |
(async/go-loop [] | |
(when (connected? client) | |
(when-let [bs (async/<! out-ch)] ;; Receive buffer | |
(try (.write client bs) ;; Write it to SocketChannel | |
(catch Exception e (log/error e))) | |
(recur)))) | |
buff-sock)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment