Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么此EventSource会反复触发消息和错误?_Javascript_Node.js_Eventsource - Fatal编程技术网

Javascript 为什么此EventSource会反复触发消息和错误?

Javascript 为什么此EventSource会反复触发消息和错误?,javascript,node.js,eventsource,Javascript,Node.js,Eventsource,客户端如下所示: 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 o

客户端如下所示:

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")
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请求的服务器端Node.js如下所示:

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")
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
每隔几秒钟触发一个错误,另外每隔几秒钟触发一个
消息
事件。但是,当触发
消息
事件时,它会发出警报
,我不知道为什么?有人能帮我弄清楚这种行为吗


编辑:刚刚检查了
消息
错误
事件上的
es.readyState
readyState
错误上显示为
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);

也就是说,我们使用
设置间隔来保持运行。唯一要监听的事件是客户端关闭连接。

首先,
“这是一个测试”
text/event stream
内容中无效。您是否尝试编写有效的响应正文?@mscdex我已编辑使其成为有效的
text/event stream
内容。现在发生的情况是,
es
每隔几秒钟触发一次
消息
事件和一次
错误
事件。但是,在
消息
事件中,
警报(e.data)
警报一个空字符串?谢谢,这很有意义。您能解释一下什么是
“连接”:“保持活动状态”
在响应标题中是否有?keep alive上有一个完整的StackOverflow标记:我认为您不需要将它用于SSE。我发现这非常有用,每个新手都会偶然发现这一点。