Skip to content

Instantly share code, notes, and snippets.

@duanebester
Last active September 26, 2021 21:06
Show Gist options
  • Save duanebester/97b111a1873047840a43132768f029ce to your computer and use it in GitHub Desktop.
Save duanebester/97b111a1873047840a43132768f029ce to your computer and use it in GitHub Desktop.
Building a Byte Buffer SocketChannel
(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