-
Notifications
You must be signed in to change notification settings - Fork 3
/
unix.clj
38 lines (33 loc) · 1.08 KB
/
unix.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(ns json-rpc.unix
(:require
[clojure.java.io :as io])
(:import
(java.io InputStreamReader PrintWriter)
(java.nio CharBuffer)
(java.nio.channels Channels)
(jnr.unixsocket UnixSocketAddress UnixSocketChannel)))
(defprotocol Client
"An UNIX socket client."
(open [this path] "Opens and returns a UNIX socket for the given path.")
(write! [this connection message] "Writes text into a UNIX socket.")
(close [this connection] "Closes the UNIX socket."))
(defrecord UnixClient []
Client
(open [this path]
(-> path
(io/file)
(UnixSocketAddress.)
(UnixSocketChannel/open)))
(write! [this channel message]
(let [buffer (CharBuffer/allocate 1024)]
(with-open [os (Channels/newOutputStream channel)
writer (PrintWriter. os)
is (Channels/newInputStream channel)
reader (InputStreamReader. is)]
(.write writer message)
(.read reader buffer)
(.flip buffer)
(str buffer)))))
(def unix-client
"An instance of [[UnixClient]]."
(->UnixClient))