v3+egg实现服务器向浏览器推送信息SSE

** egg代码**

// controller/server.ts文件中
'use strict';
const Controller = require('egg').Controller;

const { PassThrough } = require("stream");

class server extends Controller {
  async sse(ctx){
    let response = {
      code: 200,
      data: {
        id: 1,
        name: `今天你笑了吗?`
      }
    };
    ctx.set({
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      "Connection": "keep-alive"
    });
    let stream = new PassThrough();
    ctx.status = 200;

    //模拟持续服务端传值给客户端
    const interval = setInterval(() => {
      let { id } = response.data;
      if (id % 2 === 0) {
        stream.write("event: customEvents\n");
      }
      stream.write(`id: ${id}\n`);
      stream.write(`data: ${JSON.stringify(response)}\n`);
      stream.write("retry: 1000\n");
      stream.write("\n\n");
      response.data.id++;
    }, 2000);
    ctx.body = stream;
    
    //流关闭,客户端主动断开连接
    stream.on("close", () => {
      console.log("连接断开");
      clearInterval(interval);
    });
  }
}
module.exports = server;

// router.ts文件中
module.exports = app => {
 const { router, controller } = app;
 
 router.get('/sse',controller.server.sse)
}

vue代码

<template>
  <div>SSE</div>
  <div>{{id}}{{name}}</div>
  <el-button @click="close">关闭</el-button>
</template>

<script setup lang="ts">
import { ref} from 'vue'
let id=ref<number>()
let name=ref<string>()
const event = new EventSource('http://127.0.0.1:7001/sse');
event.addEventListener('open', e => {
  console.log('open:', e);
});
event.addEventListener('message', e => {
  const {data}=JSON.parse(e.data)
  id.value=data.id
  name.value=data.name
});
const close=()=>{
  event.close();
}
</script>

<style scoped lang="less">

</style>

你可能感兴趣的:(服务器,javascript,前端)