长轮询,“全球”按钮,向所有人播放?

时间:2013-11-06 00:52:00

标签: javascript go global-variables long-polling

我正在尝试实现一个全局按钮计数器,可以在任何/不同用户单击它时进行更新。 所以我的想法是,如果一个人点击按钮,我会看到我的页面实例上的计数器更新。

我目前使用长轮询技术,或者我认为,但经过审核后,我认为我将错误“广播”到所有浏览器的更新。

目前的错误是,如果我打开了两个浏览器,并且我不断点击一个浏览器,那么我点击该按钮的浏览器只会更新一半时间。它将获得1 3 5等,而另一个浏览器显示2 4 6等。

在网上查看后,我认为这可能与频道和广播到网站上的所有浏览器有关。如果有人可以帮我提供一个如何将更新发送到所有浏览器的示例,那么每次都非常感谢。

客户端:

<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>

服务器:

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)
    }
}

2 个答案:

答案 0 :(得分:6)

问题不在于Go代码(单独;请参阅PS PS),它是浏览器(Chrome)。对同一个URL发出2个请求按顺序发生,而不是并行发生。

<强>解决方案 您需要为longpoll URL添加一个唯一的时间戳来欺骗浏览器:

req.open ('GET', url+"?"+(new Date().getTime()), true); 

PS - 我通过这个问题学到了很多关于Go频道和互斥的知识。谢谢:))

PS PS - James的回答(https://stackoverflow.com/a/19803051/143225)是让服务器端Go代码一次处理多个请求的关键,因为Go通道阻塞,这意味着一次只能接收1个goroutine 。因此,OP问题的解决方案是前端和后端代码更改的组合。

答案 1 :(得分:4)

Go频道不是多播的。也就是说,如果您从频道中读取多个goroutines,则只有一个会在您向频道写入值而不是向所有读者广播时唤醒。

另一种方法是使用条件变量:

var (
    lock sync.Mutex
    cond = sync.NewCond(&lock)
)

PollResponse处理程序中,您可以使用以下条件等待:

lock.Lock()
cond.Wait()
message := strconv.Itoa(counter)
lock.Unlock()
// write message to response

PushHandler处理程序中,您可以使用以下内容广播更改:

lock.Lock()
counter += 1
cond.Broadcast()
lock.Unlock()