客户端看起来像这样:
var es = new EventSource("http://localhost:8080");
es.addEventListener("message", function(e) {
alert("e.data") //Alerts "" every couple seconds
})
es.addEventListener("error", function(e) {
alert("error") //Also fires every couple of seconds
})
var post_request = new XMLHttpRequest();
post_request.open("POST", "http://localhost:8080");
post_request.setRequestHeader("Content-Type", "text/plain");
post_request.addEventListener("readystatechange", function() {
if (post_request.readyState == 4 && post_request.status == 200) {
alert(post_request.responseText); //This works
}
})
post_request.send("This is a test")
处理 POST 请求的服务器端 Node.js 如下所示:
function process_request(request, response) {
var request_body = []
request.on("data", function(chunk) {
request_body.push(chunk)
})
request.on("end", function() {
request_body = Buffer.concat(request_body).toString()+"\n"
response.writeHead(200, {"Access-Control-Allow-Origin": "*",
"Content-Type": "text/event-stream",
"Connection": "keep-alive"
});
response.end("data: " + request_body + "\n");
})
}
如果我从客户端发送 POST 请求数据,它会按预期通过 response.end()
返回给我,但 es
每隔几秒触发一个错误,此外每隔几秒触发一个 message
事件。但是,当触发 message
事件时,它会发出警报 ""
,我不确定为什么?谁能帮我弄清楚这种行为?
编辑:刚刚检查了 message
和 error
事件上的 es.readyState
。 readyState
在 error
上为 0
,因此看起来可能是断开连接的结果。为什么会出现这种反复断线的情况呢?为什么重复的连接和断开会导致重复的消息
事件?
最佳答案
发生的情况是您正在处理用户的 SSE 请求,发回一些数据,然后关闭连接。客户端发现连接已丢失,并在几秒钟后重新连接(此重新连接是 SSE 的一项功能)。
因此,您永远不应该退出。这意味着您需要确保永远不会达到 request.on("end", ...
。
这是我之前使用过的 Node.js 中的基本 SSE 服务器:
var http = require("http");
var port = parseInt( process.argv[2] || 8080 );
http.createServer(function(request,response){
console.log("Client connected:" + request.url);
response.writeHead(200, { "Content-Type": "text/event-stream" });
var timer = setInterval(function(){
var content = "data:" + new Date().toISOString() + "\n\n";
response.write(content);
}, 1000);
request.connection.on("close", function(){
response.end();
clearInterval(timer);
console.log("Client closed connection. Aborting.");
});
}).listen(port);
console.log("Server running at http://localhost:" + port);
即我们使用 setInterval
来保持运行。唯一要监听的事件是客户端关闭连接。
关于javascript - 为什么这个EventSource会反复触发消息和错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36732404/