connection.clj
Branches > main > 66ff639 > files / src / net / bowmap / server / network / connection.clj
(ns net.bowmap.server.network.connection
(:require
[clojure.core.async :refer [io-thread]]
[clojure.spec.alpha :as s]
[clojure.stacktrace :refer [print-stack-trace]]
[clojure.tools.logging :as log]
[net.bowmap.server.network.streams :as streams])
(:import
[java.io IOException]
[java.net Socket]
[java.util.concurrent LinkedBlockingQueue]))
(defprotocol Connection
(send-frame! [conn frame]
"Sends 'frame' to the connection asynchronously. Returns nil immediately.")
(receive-frame!! [conn]
"Blocks until a frame can be read from 'conn'.
Returns nil after frames can no longer be read from the connection."))
(s/def ::connection #(satisfies? Connection %))
(defn connection
"Creates a connection from a given java.net.Socket."
[socket]
(let [input-stream (Socket/.getInputStream socket)
output-stream (Socket/.getOutputStream socket)
send-queue (LinkedBlockingQueue.)]
(Socket/.setTcpNoDelay socket true)
(io-thread
(try
(loop []
(let [frame (.take send-queue)]
(streams/write-frame!! frame output-stream)
(recur)))
(catch IOException _)
(finally
(Socket/.close socket))))
(reify Connection
(send-frame! [_ frame]
(.put send-queue frame))
(receive-frame!! [_]
(try (streams/read-frame!! input-stream)
(catch IOException _
(Socket/.close socket))
(catch Exception e
(log/warn (with-out-str (print-stack-trace e)))))))))