使用Server-sent events,和浏览器单向通信
一个网页获取新的数据通常需要发送一个请求到服务器,也就是向服务器请求的页面。 使用Server-sent events,
服务器可以在任何时刻向我们的Web页面推送数据。webpack-hot-middleware就是使用Server-sent events来发送热替换消息。
import http from 'node:http';
import { PassThrough } from 'node:stream';
import Koa from 'koa';
import serve from 'koa-static';
const app = new Koa();
app.use(serve('lib', { maxage: 0 }));
let stream;
setInterval(() => {
if (stream) {
stream.write(`event: message
data: ${ JSON.stringify({ date: new Date().toString() }) }\n\n`);
}
}, 1500);
app.use(async function(ctx, next) {
if (ctx.url === '/ssg') {
ctx.request.socket.setTimeout(0);
ctx.req.socket.setNoDelay(true);
ctx.req.socket.setKeepAlive(true);
ctx.set({
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'X-Accel-Buffering': 'no',
Connection: 'keep-alive'
});
stream = new PassThrough();
ctx.status = 200;
ctx.body = stream;
}
});
http.createServer(app.callback()).listen(5050);
在浏览器中,通过
EventSource
来创建一个连接,并监听事件。const evtSource = new EventSource('/ssg');
evtSource.addEventListener('open', function(event) {
console.log('open');
});
evtSource.addEventListener('message', function(event) {
console.log('message: ', event.data);
});