GO长时间轮询,服务器没有正确响应?

时间:2013-11-04 04:14:29

标签: javascript go long-polling

我正在尝试实现一个简单的“全局”计数器,该计数器根据点击浏览器按钮上的按钮的每个用户进行更新。例如,如果你去网站点击按钮,如果我在同一个网站上,我会看到我的计数器增加了。我试图通过长时间的民意调查来做到这一点,但面临一些问题。主要是服务器变量不会像我认为的那样回归。

服务器:

package main

import (
    "net/http"
    "log"
    "io"
    "io/ioutil"
)

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 <- 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!");
            }
        }
  };
  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>

由于某种原因,计数器变量不会从服务器返回。我相信每次单击按钮时我都会更改状态,因此longpolling函数应该获取新更新的计数器变量。如果您有任何建议,请告诉我们!

1 个答案:

答案 0 :(得分:1)

我在你的程序中看到两个问题: 1.在服务器中:

messages <- string(counter)

您应该使用“strconv”包

messages <- strconv.Itoa(counter)

string(0)将返回类似[] byte {0}而不是“0”的内容 2.在您的客户中:

function recv(msg) {
    var box = document.getElementById("counter");
    box.value += msg + "\n";
}

应该是:

function recv(msg) {
    var box = document.getElementById("counter");
    box.innerHTML += msg + "\n";
}

我不认为 p元素具有属性