Created
June 16, 2024 11:58
-
-
Save jarppe/715ec9e59fd27dcbb2ae1d0ec65b8b10 to your computer and use it in GitHub Desktop.
Simple example for obtaining a ByterChannel to Unix domain socket and converting i/o to java Input and Output streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns byte-channels-example | |
(:import (java.io InputStream | |
OutputStream) | |
(java.net UnixDomainSocketAddress | |
StandardProtocolFamily) | |
(java.nio.channels ByteChannel | |
SocketChannel | |
Channels) | |
(java.nio.charset StandardCharsets))) | |
(defn ch->in ^InputStream [^ByteChannel ch] | |
(-> (Channels/newInputStream ch) | |
(java.io.BufferedInputStream.))) | |
(defn ch->out ^OutputStream [^ByteChannel ch] | |
(-> (Channels/newOutputStream ch) | |
(java.io.BufferedOutputStream.))) | |
(defn open-docker-channel [] | |
(doto (SocketChannel/open StandardProtocolFamily/UNIX) | |
(.connect (UnixDomainSocketAddress/of "/var/run/docker.sock")) | |
(.finishConnect))) | |
(defn get-docker-version [] | |
(with-open [ch (open-docker-channel)] | |
(doto (ch->out ch) | |
(.write (-> (str "GET /version HTTP/1.0\r\n" | |
"Host: docker.com\r\n" | |
"\r\n") | |
(.getBytes StandardCharsets/UTF_8))) | |
(.flush)) | |
(let [in (ch->in ch)] | |
(loop [c (.read in)] | |
(when-not (= c -1) | |
(when-not (= c (int \return)) | |
(print (char c))) | |
(recur (.read in))))))) | |
(comment | |
(get-docker-version) | |
;=> | |
; HTTP/1.0 200 OK | |
; Api-Version: 1.45 | |
; Content-Type: application/json | |
; Date: Sun, 16 Jun 2024 11:53:10 GMT | |
; Docker-Experimental: false | |
; Ostype: linux | |
; Server: Docker/26.1.1 (linux) | |
; | |
; {"Platform":{"Name":"Docker Desktop 4.30.0 (149282)"},"Components":[{"Name"... | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment