websocket - (Go) Comparing everchanging variable in ws loop -
working on loop receives messages , processes them accordingly, websocket echo-er keep-alives , authentication, , i've been stuck in keep-alive part little while now.
the concept simple, when server starts create goroutine ticker, , initialize uint64 pointer, each time ticker ticks (every 2 seconds), increment pointer atomic.adduint64(clockticks, 1), each websocket connection goroutine, check variable every tick compare , atomic.loaduint64(clockticks), , send ping/pong message.
edit: seems blocking loop until message received, result:
i := atomic.loaduint64(clockticks) if != cur { cur = if act != true { fmt.println("quit nao u filthy bot.") return } else { fmt.println("keep going.") act = false } }
in snippet, := atomic.loaduint64(clockticks) & if block runs when message sent (prints "keep going." on msg), not want, want snippet run every iteration, , "keep going." & "quit nao ..." trigger everytime clockticks incremented
here's important code parts, i'm using go , gorilla's websockets library:
func clock() { clockticks = new(uint64) *clockticks = 0 clock := time.newticker(authintervals).c { <-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 { := atomic.loaduint64(clockticks) if != cur { /* triggers when receive msg */ cur = 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: in irc suggested maybe ws.readmessage blocking, i'm not sure (he says ioutil.readall used in ws.readmessage implementation blocking it, , he's pretty sure it)
the websocket read methods call network connection read method data network. because network connection read method blocks, webscocket methods block.
to send pings, use ticker in write loop as in gorilla chat example or run separate goroutine pings as in gorilla command example.
Comments
Post a Comment