브라우저 단추에서 단추를 클릭하는 모든 사용자를 기반으로 업데이트되는 간단한 "전역"카운터를 구현하려고합니다. 예를 들어 웹 사이트에서 버튼을 클릭하면 같은 웹 사이트에있는 경우 카운터가 증가합니다. 나는 긴 폴링으로이 일을 추구했지만 몇 가지 문제에 직면 해있다. 주로 서버 변수가 돌아 오지 않는다고 생각합니다.GO에서 긴 폴링, 서버가 적절하게 응답하지 않습니까?
서버 :
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 :
shamless 플러그가 : 내가 당신을 위해 모든 상용구을 담당 라이브러리라는 golongpoll를 만들었습니다. https://github.com/jcuga/golongpoll – jCuga