sse-client.ts
export default class SSEClient {
source: EventSource;
element: HTMLElement;
constructor(url) {
this.source = new EventSource(url || 'http://127.0.0.1:8844/stream');
this.source.onopen = this.onOpen.bind(this);
this.source.onerror = this.onError.bind(this);
this.source.addEventListener('connecttime', this.onConnectTime.bind(this), false);
this.source.onmessage = this.onMessage.bind(this);
}
// eslint-disable-next-line class-methods-use-this
onOpen(event) {
console.log('onOpen-event :>> ', event);
}
// eslint-disable-next-line class-methods-use-this
one rror(event) {
console.log('onError-event :>> ', event);
}
// eslint-disable-next-line class-methods-use-this
onConnectTime(event) {
console.log('onConnectTime-event :>> ', event);
}
// eslint-disable-next-line class-methods-use-this
onMessage(event) {
console.log('onMessage-event :>> ', event);
const localstore = useLocalStore();
localstore.setAdvertiseMsg([event.data]);
}
close() {
console.log('close :>> ');
this.source.close();
}
}
// 使用示例
// const sseClient = new SSEClient('http://127.0.0.1:8844/stream', 'example');
// 当你想关闭连接时,调用sseClient.close();
server.js
const http = require('http');
http.createServer(function (req, res) {
const fileName = `.${req.url}`;
if (fileName === './stream') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
res.write('retry: 10000\n');
res.write('event: connecttime\n');
res.write(`data: ${new Date()}\n\n`);
res.write(`data: ${new Date()}\n\n`);
interval = setInterval(function () {
res.write(`data: ${new Date()}\n\n`);
}, 60000);
req.connection.addListener(
'close',
function () {
clearInterval(interval);
},
false
);
}
}).listen(8844, '127.0.0.1');
标签:node,console,res,server,source,new,sse,close,event
From: https://www.cnblogs.com/yoona-lin/p/17932623.html