为什么此EventSource重复触发消息和错误
Why is this EventSource repeatedly triggering message and error?
客户端如下所示:
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
,所以看起来可能是断开连接的结果。为什么会发生这种反复的断开连接?为什么重复的连接和断开会导致重复的message
事件?
正在处理用户的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
来保持运转。唯一要侦听的事件是客户端关闭连接。
相关文章:
- jQuery在输入下验证post错误消息
- ng消息仅在触摸时显示错误,并在错误的初始显示上转换
- 解析云代码错误:解析.错误{代码:141,消息:“未调用成功/错误”}
- 在AngularJs中隐藏默认错误消息
- 如果用户输入的长度小于最小长度,则显示错误消息
- 使用ASP.NET CustomValidator避免重复的错误消息
- KOValidation在错误消息中获取可观察值、$index()、$data等
- 更改精细上载中的错误消息
- 如何在页面刷新时隐藏错误消息
- 如何显示错误消息
- 滑块未显示,控制台中没有错误消息
- 表单提交没有'如果为空,则不会显示错误消息
- 为什么我的Alexa技能测试显示正确的lambda输出,但在开发人员控制台中测试时却给出错误消息
- 隐藏错误消息“;未选择文件”;asp:fileUpload的文本
- 如何在消息中抛出tv4错误
- 登录时显示自定义错误消息
- jQuery AJAX 调用以发布消息 - 错误 堆栈空间不足
- 不断收到'向云PubSub发送测试消息错误…'Google Cloud PubSub
- 抑制WebBrowser JavaScript消息错误
- 在Chrome中解析SVG路径日志消息错误