 (defonce ^:private sync-obj (Object.))
 
 
+
+
+
+(defn- shutdown-socket
+  "Close the server-socket"
+  []
+  (locking sync-obj
+    (let [ss @shim-socket]
+      (swap! shim-socket #(-> %
+                              (dissoc ::swagger)
+                              (dissoc ::input)
+                              (dissoc ::output)
+                              (dissoc ::socket)))
+      (when-let [inputa (::input ss)]
+        (doseq
+          [input [inputa]]
+          (try
+            (.close ^InputStream input)
+            (catch Exception e nil)))
+        )
+      (when-let [outputs (::output ss)]
+        (doseq [output [outputs]]
+          (try
+            (.close ^OutputStream output)
+            (catch Exception e nil)))
+        )
+      (when-let [sockets (::socket ss)]
+        (doseq [socket [sockets]]
+          (try
+            (.close ^Socket socket)
+            (catch Exception e nil)))
+        )
+      )))
 
 (defn send-message
   [message]
   (let [b64 (fu/encode-body message)]
-    (doseq [out-x (::output @shim-socket)]
-      (let [out (BufferedWriter. (OutputStreamWriter. ^OutputStream out-x "UTF-8"))]
-        (locking sync-obj
-          (.write out b64)
-          (.write out "\n")
-          (.flush out))))))
+    (try
+      (doseq [out-x (filter identity [(::output @shim-socket)])]
+        (let [out (BufferedWriter. (OutputStreamWriter. ^OutputStream out-x "UTF-8"))]
+          (locking sync-obj
+            (.write out b64)
+            (.write out "\n")
+            (.flush out))))
+      (catch IOException io
+        (do
+          (clojure.tools.logging/log :error io "Failed to send message")
+          (shutdown-socket)
+          ))
+      )))
 
 (defn- shutdown
   "Close the server-socket"

(defn http-handler
  [req]
  (if-let [swagger (::swagger @shim-socket)]
    (let [app (make-app swagger)]
      (app req))
    {:status 404 :body "I'm swagger-less"}
    ))

(defonce end-server (atom nil))

      (reset! shim-socket nil)
      (when-let [inputa (::input ss)]
        (doseq
          [input [inputa]]
          (try
            (.close ^InputStream input)
            (catch Exception e nil)))
        )
      (when-let [outputs (::output ss)]
        (doseq [output [outputs]]
          (try
            (.close ^OutputStream output)
            (catch Exception e nil)))
        )
      (when-let [sockets (::socket ss)]
        (doseq [socket [sockets]]
          (try
            (.close ^Socket socket)
            (catch Exception e nil)))
