From 58373496f024f56058d98e2a967204a429cccbea Mon Sep 17 00:00:00 2001 From: Nicholas Kariniemi Date: Fri, 10 Oct 2014 22:48:39 +0300 Subject: [PATCH] Use transit for communication for possible speed improvements --- project.clj | 4 +++- src/clj/grub/websocket.clj | 19 ++++++++++++++++--- src/cljs/grub/websocket.cljs | 9 +++++---- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/project.clj b/project.clj index 38b5faa..8dc8786 100644 --- a/project.clj +++ b/project.clj @@ -18,7 +18,9 @@ [clj-webdriver "0.6.1" :exclusions [org.clojure/core.cache]] [sablono "0.2.17"] [cljs-uuid "0.0.4"] - [net.polyc0l0r/hasch "0.2.3"]] + [net.polyc0l0r/hasch "0.2.3"] + [com.cognitect/transit-clj "0.8.259"] + [com.cognitect/transit-cljs "0.8.188"]] :profiles {:uberjar {:aot :all} :dev {:dependencies [[midje "1.6.3"]]}} :min-lein-version "2.1.2" diff --git a/src/clj/grub/websocket.clj b/src/clj/grub/websocket.clj index 57b4a0e..0f63862 100644 --- a/src/clj/grub/websocket.clj +++ b/src/clj/grub/websocket.clj @@ -1,18 +1,31 @@ (ns grub.websocket (:require [grub.db :as db] [org.httpkit.server :as httpkit] - [clojure.core.async :as a :refer [! chan go]])) + [clojure.core.async :as a :refer [! chan go]] + [cognitect.transit :as t]) + (:import [java.io ByteArrayInputStream ByteArrayOutputStream])) (defn disconnected [status ws-channel to from] (println "Client disconnected:" (.toString ws-channel) "with status" status) (a/close! to) (a/close! from)) +(defn write-msg [msg] + (let [out (ByteArrayOutputStream. 4096) + writer (t/writer out :json)] + (t/write writer msg) + (.toString out))) + +(defn read-msg [msg] + (let [in (ByteArrayInputStream. (.getBytes msg)) + reader (t/reader in :json)] + (t/read reader))) + (defn add-connected-client! [ws-channel to from] (println "Client connected:" (.toString ws-channel)) (a/go-loop [] (if-let [event (! chan]] - [cljs.reader] goog.net.WebSocket goog.events.EventHandler goog.events.EventTarget - [hasch.core :as hasch]) + [cognitect.transit :as t]) (:require-macros [cljs.core.async.macros :refer [go go-loop]] [grub.macros :refer [log logs]])) (def server-url (str "ws://" (.-host (.-location js/document)))) (def pending-msg (atom nil)) +(def reader (t/reader :json)) +(def writer (t/writer :json)) (defn send-pending-msg [websocket] (when (and (.isOpen websocket) (not (nil? @pending-msg))) - (.send websocket (pr-str @pending-msg)) + (.send websocket (t/write writer @pending-msg)) (reset! pending-msg nil))) (defn on-connected [websocket event] @@ -22,7 +23,7 @@ (send-pending-msg websocket)) (defn read-msg [msg] - (cljs.reader/read-string (.-message msg))) + (t/read reader (.-message msg))) (defn connect-client! [in out] (let [handler (goog.events.EventHandler.)