summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChristian Pointner <equinox@helsinki.at>2015-07-16 23:23:44 (GMT)
committerChristian Pointner <equinox@helsinki.at>2015-07-16 23:23:44 (GMT)
commitc5e73c3fb3a1ef94dfbadbfc06e69cbf74b289a8 (patch)
tree73d997ce7d275b1a9020a1b5ee86178e8b5fb4a5
parenta17956bde502c6629732b4710553fb3a968ec700 (diff)
sending actual time to websocket clients
-rw-r--r--src/helsinki.at/rhrdtime/rhrdtime.go43
1 files changed, 30 insertions, 13 deletions
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")
}
}()