GO 中的长时间轮询,服务器响应不当
Long Polling in GO, Server Not Responding Appropriately?
我正在尝试实现一个简单的"全局"计数器,该计数器会根据单击浏览器按钮上的每个用户进行更新。例如,如果您转到该网站并单击按钮,如果我在同一网站上,我会看到计数器增加。我试图通过长时间的民意调查来做到这一点,但面临一些问题。主要是服务器变量没有像我认为的那样返回。
服务器:
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>
由于某种原因,计数器变量未从服务器返回。我相信每次单击按钮时我都会更改状态,因此长轮询函数应该获取新更新的计数器变量。如果您有任何建议,请告诉我!
我在你们的程序中看到了两个问题: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元素具有值属性
相关文章:
- 带Jquery的wep API,加载资源失败:服务器响应状态为404(未找到)
- 如何在 http 上调用 end().服务器响应对象
- 将服务器响应格式化为人类可读
- 尝试获取服务器响应
- 如何在 Javascript 函数中拦截 Web 服务器响应
- 如何从服务器响应中显示phonegap中的图像
- Nodejs-websocket:如何在没有服务器响应的情况下连续发送客户端消息
- 正在分析Meteor中的错误服务器响应
- 正在从LWIP服务器响应中检索16位整数
- 可以´t从对象XMLHttpRequest获取服务器响应
- 试图理解返回javascript方法的服务器响应
- AJAX 中的常见服务器响应页原因
- 节点服务器响应错误: process.nextTick(function(){throw err;});.
- GO 中的长时间轮询,服务器响应不当
- 在 Iframe 中发布服务器响应
- Jquery 响应从服务器响应中修剪值
- 在铁表单提交后检查服务器响应
- 量角器单击链接并将服务器响应与文件进行比较
- 如何确定 Node .js服务器响应是否已停止
- 当服务器响应缓慢时,jQuery 在加载/就绪时不触发