将 SSE 与 NodeJs 一起使用时的多个 http 请求
Multiple http requests while using SSE with NodeJs
我正在尝试实现一个应用程序,我需要做的一件事是使用服务器发送事件将数据从服务器发送到客户端。 SSE 的基础是有一个连接,在这个连接不关闭的情况下来回传输数据。我现在遇到的问题是,每次我使用 EventSource()
从客户端发出 HTTP 时,都会发出多个请求。
客户:
const eventSource = new EventSource('http://localhost:8000/update?nick='+username+'&game='+gameId)
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data)
console.log(data)
}
服务器(Node.Js):
case '/update':
res.writeHead(200,{
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
res.write('data: 1')
res.write('\n\n')
res.end('{}')
break
This 是我在 chrome 开发工具中看到的。当客户端尝试使用 SSE 进行连接时,它会向服务器发出多个请求。但是应该只提出一个请求。
你们知道如何解决这个问题吗?提前谢谢你。
这样做的方法是不包括 res.end()
,因为必须保持连接。最重要的是,我必须跟踪用户发出的 http 请求的响应,因此我使用以下方法创建了一个不同的模块:
let responses = []
module.exports.remember = function(res){
responses.push(res)
}
module.exports.forget = function(res){
let pos = responses.findIndex((response)=>response===res)
if(pos>-1){
responses.splice(pos, 1)
}
}
module.exports.update = function(data){
for(let response of responses){
response.write(`data: ${data} \n\n`)
}
}
这样就可以访问响应对象并使用函数 update()
将数据发送到连接的客户端。
我正在尝试实现一个应用程序,我需要做的一件事是使用服务器发送事件将数据从服务器发送到客户端。 SSE 的基础是有一个连接,在这个连接不关闭的情况下来回传输数据。我现在遇到的问题是,每次我使用 EventSource()
从客户端发出 HTTP 时,都会发出多个请求。
客户:
const eventSource = new EventSource('http://localhost:8000/update?nick='+username+'&game='+gameId)
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data)
console.log(data)
}
服务器(Node.Js):
case '/update':
res.writeHead(200,{
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
res.write('data: 1')
res.write('\n\n')
res.end('{}')
break
This 是我在 chrome 开发工具中看到的。当客户端尝试使用 SSE 进行连接时,它会向服务器发出多个请求。但是应该只提出一个请求。
你们知道如何解决这个问题吗?提前谢谢你。
这样做的方法是不包括 res.end()
,因为必须保持连接。最重要的是,我必须跟踪用户发出的 http 请求的响应,因此我使用以下方法创建了一个不同的模块:
let responses = []
module.exports.remember = function(res){
responses.push(res)
}
module.exports.forget = function(res){
let pos = responses.findIndex((response)=>response===res)
if(pos>-1){
responses.splice(pos, 1)
}
}
module.exports.update = function(data){
for(let response of responses){
response.write(`data: ${data} \n\n`)
}
}
这样就可以访问响应对象并使用函数 update()
将数据发送到连接的客户端。