我正在尝试实现一个简单的“全局”计数器,该计数器根据点击浏览器按钮上的按钮的每个用户进行更新。例如,如果您转到网站并单击按钮,如果我在同一个网站上,我会看到我这边的计数器增加。我试图通过长轮询来做到这一点,但我面临着一些问题。主要是服务器变量没有像我认为的那样回来。服务器:package mainimport ( "net/http" "log" "io" "io/ioutil")var messages chan string = make(chan string, 100)var counter = 0func PushHandler(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) if err != nil { w.WriteHeader(400) } counter += 1 messages <- string(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(":8005", nil) if err != nil { log.Fatal("ListenAndServe: ", err) }}客户端:<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.value += 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!"); } }由于某种原因,计数器变量没有从服务器返回。我相信每次单击按钮时我都会更改状态,因此 longpolling 函数应该获取新更新的计数器变量。如果您有任何建议,请让我知道!
1 回答
- 1 回答
- 0 关注
- 193 浏览
添加回答
举报
0/150
提交
取消