connection.clj

Branches > main > cc5984f > files / src / net / bowmap / transport / connection.clj

(ns net.bowmap.transport.connection
  (:require
   [clojure.core.async :refer [<!! >!! chan io-thread close!]]
   [net.bowmap.transport.streams :as streams])
  (:import
   [java.io EOFException]
   [java.net Socket SocketException]))

; Connection can be sent and received frames?
; It is the I/O part of the client
; Clients are then I/O free

(defn connection [socket]
  (let [serverbound-frames (chan 64)
        clientbound-frames (chan 64)
        input-stream (Socket/.getInputStream socket)
        output-stream (Socket/.getOutputStream socket)
        conn {::close-fn (fn [] (Socket/.close socket))
              ::serverbound-frames serverbound-frames
              ::clientbound-frames clientbound-frames}]
    (io-thread
      (try
        (loop []
          (>!! serverbound-frames (streams/read-frame!! input-stream))
          (recur))
        (catch EOFException _)
        (catch SocketException _)
        (finally
          (close! serverbound-frames)
          (Socket/.close socket))))
    (io-thread
      (try
        (loop []
          (when-some [frame (<!! clientbound-frames)]
            (streams/write-frame!! frame output-stream)
            (recur)))
        (finally
          (close! clientbound-frames))))
    conn))