vue接收event-stream 流式数据并回显

如果服务器返回的是 event-stream 流式数据,你可以使用 EventSource 来处理这些数据。EventSource 是一种服务器发送事件(Server-Sent Events, SSE)的 API,它允许服务器向客户端推送实时更新。

1.在 Vue 组件中使用 EventSource:

<template>
  <div>
    <button @click="startEventSource">开始接收事件</button>
    <button @click="stopEventSource">停止接收事件</button>
    <div v-for="event in events" :key="event.id">
      {{ event.data }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'EventSourceExample',
  data() {
    return {
      events: [],
      eventSource: null
    };
  },
  methods: {
    startEventSource() {
      if (!this.eventSource) {
        this.eventSource = new EventSource('/api/stream');
        this.eventSource.onmessage = this.handleMessage;
        this.eventSource.onerror = this.handleError;
      }
    },
    stopEventSource() {
      if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
      }
    },
    handleMessage(event) {
      // 处理接收到的消息
      console.log('收到消息:', event.data);
      this.events.push({ id: this.events.length, data: event.data });
    },
    handleError(event) {
      // 处理错误
      console.error('EventSource 错误:', event);
      this.stopEventSource();
    }
  },
  beforeDestroy() {
    // 组件销毁前停止 EventSource
    this.stopEventSource();
  }
};
</script>

2.服务器端示例(假设使用 Node.js 和 Express):

const express = require('express');
const app = express();

app.get('/api/stream', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  // 模拟实时事件
  setInterval(() => {
    res.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
  }, 1000);
});

app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

在这个示例中,客户端使用 EventSource 来接收服务器发送的实时事件。服务器端使用 Express 创建一个 GET 路由,返回 event-stream 类型的数据。客户端在接收到事件时,会调用 handleMessage 方法来处理这些事件。

请注意,EventSource 是一种单向通信方式,即只能从服务器向客户端发送数据。如果你需要双向通信,可能需要使用 WebSocket 或其他双向通信技术。

文章来源CodeGeeX 只作记录

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐