EventSource基本使用

901 阅读1分钟
  • EventSource是一个单向的通信协议,数据只能从服务器发送到客户端,HTTP请求开启连接后,服务器可以持续发送消息,知道连接关闭。
  • EventSource 只能发送 纯文本 格式的数据,使用的是 UTF-8 编码。消息结构是简单的文本流,每条消息之间以换行符分隔。
  • EventSource 自带 自动重连 机制,默认情况下如果连接断开,浏览器会尝试自动重连,而无需客户端手动处理
  • 代码示例(vue + exrpess)
<script setup>
import { ref } from "vue"
const userList = ref([])
const handleSend=async ()=>{
  const eventSource = new EventSource("/api/user");

  eventSource.onopen = (e) => {
    console.log("The connection has been established.");
    console.log(eventSource.readyState);
  };
  eventSource.onmessage=function(e){
    const val = JSON.parse(e.data);
    userList.value = val;
  }
  eventSource.onerror=function(e){
    console.log(e)
  }
}

</script>
async getUserList(req,res,next){
  try{
      res.setHeader('Content-Type', 'text/event-stream');
      res.setHeader("Connection", "keep-alive");

      setInterval(()=>{
          const userList=[
              {
                  userId:"1001"+Math.floor(Math.random()*100),
                  userName:"foo"
              },
              {
                  userId:"1002"+Math.floor(Math.random()*100),
                  userName:"bar"
              }
          ]
          const value = JSON.stringify(userList);
          res.write(`data:${value}\n\n`)
      },1000)
  }  catch (e) {
      console.log(e.message)
  }
}
  • 在 Express 中,如果你已经通过 res.write() 向客户端发送了 Server-Sent Events(SSE)数据,但前端的 onmessage 事件没有接收到数据
  • Server-Sent Events 的数据格式非常严格,必须遵循以下规则:
    • 每条消息必须以 data: 开头,后面跟上消息内容。
    • 每条消息必须以两个换行符 \n\n 结尾,表示消息的结束。
    • 确保在服务器端设置了正确的 Content-Type。它必须是 text/event-stream,这是 SSE 连接所要求的格式。