Skip to content

Commit

Permalink
Playing with http socket server
Browse files Browse the repository at this point in the history
  • Loading branch information
djblue committed Aug 10, 2020
1 parent af570fa commit 94e8924
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions src/portal/http_socket_server.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
(ns portal.http-socket-server
(:require [clojure.java.io :as io]
[clojure.string :as string])
(:import [java.net ServerSocket]))

(defn handler [request]
{:status 200
:headers {"Content-Type" "application/json"}
:body "{\"hello\": \"world\"}"})

(defn parse-request [in]
(let [[req-line & headers]
(loop [headers []]
(let [line (.readLine in)]
(if (string/blank? line)
headers
(recur (conj headers line)))))
[method path] (string/split req-line #" ")]
{:method method
:uri path
:headers (->> headers
(map #(string/split % #": "))
(into {}))}))

(def messages
{200 "OK"
404 "Not Found"})

(defn format-response [response]
(let [{:keys [status body headers]} response
headers (assoc headers "Content-Length" (count (.getBytes body)))]
(str "HTTP/1.1 " status " " (get messages status) "\r\n"
(string/join
(map (fn [[k v]] (str k ": " v "\r\n")) headers))
"\r\n"
body)))

(defn start-worker-thread [client-socket request-handler]
(.start
(Thread.
(fn []
(with-open [in (io/reader (.getInputStream client-socket))
out (io/writer (.getOutputStream client-socket))]
(let [request (parse-request in)
response (request-handler request)
{:keys [status body]} response]
(.write out (format-response response)))
(.flush out))))))

(defn start []
(let [server-socket (ServerSocket. 4444)
port (.getLocalPort server-socket)
_ (println "Serv: Awaiting connection on port " port)]
(while true
(let [client-socket (.accept server-socket)]
(start-worker-thread client-socket #'handler)))))

(defn stop [])

(defn -main []
(start))

0 comments on commit 94e8924

Please sign in to comment.