From c5e73c3fb3a1ef94dfbadbfc06e69cbf74b289a8 Mon Sep 17 00:00:00 2001 From: Christian Pointner Date: Fri, 17 Jul 2015 01:23:44 +0200 Subject: sending actual time to websocket clients diff --git a/src/helsinki.at/rhrdtime/rhrdtime.go b/src/helsinki.at/rhrdtime/rhrdtime.go index c90c699..5a9f0d0 100644 --- a/src/helsinki.at/rhrdtime/rhrdtime.go +++ b/src/helsinki.at/rhrdtime/rhrdtime.go @@ -26,15 +26,33 @@ package main import ( "fmt" - "net/http" "time" "flag" + "net/http" + "encoding/json" "github.com/codegangsta/martini" "github.com/gorilla/websocket" "github.com/tuxychandru/pubsub" ) +type timeUpdate struct { + Timestamp int64 `json:"timestamp"` + Week uint8 `json:"week"` +} + +func getTimeUpdate() []byte { + now := time.Now() + + update := timeUpdate{now.Unix(), 1} + update_json, err := json.Marshal(update) + if err != nil { + fmt.Println(err) + return []byte{'{', '}'} + } + return update_json +} + func goTalkWithClient(w http.ResponseWriter, r *http.Request, ps *pubsub.PubSub) { ws, err := websocket.Upgrade(w, r, nil, 1024, 1024) if _, ok := err.(websocket.HandshakeError); ok { @@ -46,11 +64,16 @@ func goTalkWithClient(w http.ResponseWriter, r *http.Request, ps *pubsub.PubSub) } fmt.Println("Client connected", ws.RemoteAddr()) - publish_to_all_chan := ps.Sub("timeupdate") + timeupdate_chan := ps.Sub("timeupdate") + defer ps.Unsub(timeupdate_chan, "timeupdate") + + update_json := getTimeUpdate() + if err := ws.WriteMessage(websocket.TextMessage, update_json); err != nil { + return + } - for jsonupdate := range publish_to_all_chan { + for jsonupdate := range timeupdate_chan { if err := ws.WriteMessage(websocket.TextMessage, jsonupdate.([]byte)); err != nil { - ps.Unsub(publish_to_all_chan, "timeupdate") return } } @@ -66,7 +89,7 @@ func RunMartini(ps *pubsub.PubSub) { } func main() { - interval_s := flag.String("interval", "15s", "the interval between updates, default 15s") + interval_s := flag.String("interval", "15s", "the interval between updates, default: 15s") help := flag.Bool("help", false, "show usage") flag.Parse() @@ -85,14 +108,8 @@ func main() { ticker := time.NewTicker(interval) go func() { - for t := range ticker.C { - tj, err := t.MarshalJSON() - if err != nil { - fmt.Println(err) - return - } - fmt.Println("Tick at: ", t) - ps.Pub(tj, "timeupdate"); + for _ = range ticker.C { + ps.Pub(getTimeUpdate(), "timeupdate") } }() -- cgit v0.10.2