connection.clj
Branches > main > e234a79 > files / src / net / bowmap / transport / connection.clj
(ns net.bowmap.transport.connection
"A connection to the Minecraft server."
(:require
[clojure.core.async :refer [<!! >!! chan io-thread close!]]
[net.bowmap.transport.streams :as streams])
(:import
[java.io EOFException]
[java.net Socket SocketException]))
(defn connection
"Creates a connection from a java.net.Socket
Connections can be sent and can receive frames via channels."
[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))