I am trying to implement a global button counter that updates as any/different users click it. So the idea is if one person clicks the button, I see the counter update on my instance of the page.
I currently have the long polling technique working, or so I think, but after review I believe I have an error with "broadcasting" the update to all browsers.
The error currently is that if for example I have two browsers open, and I continuously click on one browser, that browser that I click the button only updates half the time. It will get 1 3 5 etc while the other browser displays 2 4 6 etc.
After reviewing online, I think this may have to do with channels and broadcasting to all those browsers that are on the site. If anyone can help me with an example of how I might send the update to all browsers, every time, I'd really appreciate it.
Client:
<html>
<script language=javascript>
function longpoll(url, callback) {
var req = new XMLHttpRequest ();
req.open ('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
callback(req.responseText);
longpoll(url, callback);
} else {
alert ("long-poll connection lost");
}
}
};
req.send(null);
}
function recv(msg) {
var box = document.getElementById("counter");
box.innerHTML += msg + "\n";
}
function send() {
var box = document.getElementById("counter");
var req = new XMLHttpRequest ();
req.open ('POST', "/push?rcpt=", true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
} else {
alert ("failed to send!");
}
}
};
req.send("hi")
//box.innerHTML += "test" ;
}
</script>
<body onload="longpoll('/poll', recv);">
<h1> Long-Poll Chat Demo </h1>
<p id="counter"></p>
<button onclick="send()" id="test">Test Button</button>
</body>
</html>
Server:
package main
import (
"net/http"
"log"
"io"
// "io/ioutil"
"strconv"
)
var messages chan string = make(chan string, 100)
var counter = 0
func PushHandler(w http.ResponseWriter, req *http.Request) {
//body, err := ioutil.ReadAll(req.Body)
/*if err != nil {
w.WriteHeader(400)
}*/
counter += 1
messages <- strconv.Itoa(counter)
}
func PollResponse(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, <-messages)
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/poll", PollResponse)
http.HandleFunc("/push", PushHandler)
err := http.ListenAndServe(":8010", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
send()
function on the client side, which is activated whenever a user pushes the button – Arreolafmt.Println()
calls to confirm WHEN those calls are going through as opposed to WHEN the poll responses are going through. I'll run a local test in an hour or so and see what results I can get (I'm at work currently and can't test your code) – Rudolf