EventSource
EventSource 是一种基于事件的服务器发送事件协议,允许网页或应用程序创建一个实时通过连接发送的事件流。
ts
import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/sse',
response(req, res) {
const sse = createSSEStream(req, res)
let count = 0
const timer = setInterval(() => {
sse.write({
event: 'count',
data: { count: ++count },
})
if (count >= 10) {
sse.write({ event: 'close' })
sse.end()
clearInterval(timer)
}
}, 1000)
},
})
ts
const es = new EventSource('/api/sse')
es.addEventListener('count', (e) => {
console.log(e.data)
})
es.addEventListener('close', () => {
es.close()
console.log('close')
})