From 5c343eda1e8ba95db0ab2eea1451fcade3ea1537 Mon Sep 17 00:00:00 2001 From: INGSOL Date: Tue, 4 Sep 2018 10:25:21 +0200 Subject: [PATCH] Full circle working sockets --- Gopkg.toml | 7 +++++- client/src/cljs/cse_client/core.cljs | 16 ++++++++++++++ server.go | 1 + websockets.go | 32 ++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 websockets.go diff --git a/Gopkg.toml b/Gopkg.toml index edddc4a..d649301 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -8,4 +8,9 @@ [[constraint]] name = "github.com/gobuffalo/packr" - version = "1.13.1" \ No newline at end of file + version = "1.13.1" + +[[constraint]] + name = "github.com/gorilla/websocket" + version = "1.4.0" + diff --git a/client/src/cljs/cse_client/core.cljs b/client/src/cljs/cse_client/core.cljs index 90c71d2..4b4aaed 100644 --- a/client/src/cljs/cse_client/core.cljs +++ b/client/src/cljs/cse_client/core.cljs @@ -1,5 +1,6 @@ (ns cse-client.core (:require [kee-frame.core :as k] + [kee-frame.websocket :as websocket] [ajax.core :as ajax] [re-interval.core :as re-interval] [re-frame.core :as rf])) @@ -16,6 +17,21 @@ :start [:poll/start] :stop [:poll/stop]}) +(k/reg-controller :websocket-controller + {:params #(when (-> % :handler (= :index)) true) + :start [:start-websockets] + :stop [:stop-websockets]}) + +(k/reg-event-fx :start-websockets + (fn [_ _] + {::websocket/open {:path "/ws" + :dispatch ::socket-message-received + :format :json}})) + +(k/reg-event-db ::socket-message-received + (fn [db event] + db)) + (k/reg-chain :poll/tick (fn [_ _] {:http-xhrio {:method :get diff --git a/server.go b/server.go index 18f0342..8a02f59 100644 --- a/server.go +++ b/server.go @@ -52,6 +52,7 @@ func Server(command chan string) { command <- "pause" json.NewEncoder(w).Encode(Simulator{ID: "id-1", Name: "Clock", Status: "-"}) }) + router.HandleFunc("/ws", WebsocketHandler) router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(box))) diff --git a/websockets.go b/websockets.go new file mode 100644 index 0000000..316fccb --- /dev/null +++ b/websockets.go @@ -0,0 +1,32 @@ +package main + +import ( + "github.com/gorilla/websocket" + "net/http" + "log" +) + +var upgrader = websocket.Upgrader{} + +func WebsocketHandler(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + conn.WriteMessage(websocket.TextMessage, []byte("{\"Hello\": \"Mordi\"}")) + if err != nil { + log.Print("upgrade:", err) + return + } + defer conn.Close() + for { + mt, message, err := conn.ReadMessage() + if err != nil { + log.Println("read:", err) + break + } + log.Printf("recv: %s", message) + err = conn.WriteMessage(mt, message) + if err != nil { + log.Println("write:", err) + break + } + } +} \ No newline at end of file