Working on a loop that receives messages and processes them accordingly, basically a websocket echo-er with keep-alives and authentication, and I've been stuck in the keep-alive part for a little while now.
The concept is simple, when the server starts I create a goroutine with a ticker, and I initialize a uint64 pointer, each time that ticker ticks (every 2 seconds), I increment the pointer with atomic.AddUint64(clockTicks, 1), then for each websocket connection goroutine, I check the variable every tick with a compare and atomic.LoadUint64(clockTicks), and I send a ping/pong message.
Edit: Seems like something is blocking the for loop until a message is received, result:
i := atomic.LoadUint64(clockTicks)
if i != cur {
cur = i
if act != true {
fmt.Println("Quit Nao U filthy bot.")
return
} else {
fmt.Println("Keep Going.")
act = false
}
}
In this snippet, i := atomic.LoadUint64(clockTicks) & all the if block only runs when i message is sent (Prints "Keep Going." on msg), which is not what I want, I want the snippet to run every for iteration, and "Keep Going." & "Quit nao ..." to trigger everytime clockTicks is incremented
Here's the important code parts, I'm using Go and Gorilla's Websockets library:
func Clock() {
clockTicks = new(uint64)
*clockTicks = 0
clock := time.NewTicker(authIntervals).C
for {
<-clock
atomic.AddUint64(clockTicks, 1)
}
}
var wsu = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: OriginHandler,
}
func serveWS(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
ws, err := wsu.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer ws.Close()
cur := atomic.LoadUint64(clockTicks)
var act, val = true, false
for {
i := atomic.LoadUint64(clockTicks)
if i != cur { /* Only triggers when I receive a msg */
cur = i
if act != true {
fmt.Println("Quit Nao U filthy bot.")
return
} else {
fmt.Println("Keep Going.")
act = false
}
}
mtype, p, err := ws.ReadMessage()
if err != nil {
return
}
...
}
Edit 2: Someone in IRC suggested that maybe ws.ReadMessage is blocking, but I'm not really sure (He says ioutil.ReadAll used in ws.ReadMessage implementation is blocking it, and he's pretty sure about it)