Gin(后端)和 Vue3(前端)中实现 Server-Sent Events(SSE)推送

Gin(后端)和 Vue3(前端)中实现 Server-Sent Events(SSE)推送,主要分为以下几个步骤:

后端(Gin)实现 SSE

Gin 框架可以使用 c.SSEvent 方法来推送 SSE 事件。

1. 安装 Gin

确保你的 Go 项目已安装 gin

sh 复制代码
go get -u github.com/gin-gonic/gin
2. Gin SSE 服务器

创建一个 SSE 端点 /sse,用于持续向前端推送消息:

go 复制代码
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// SSE 推送
	r.GET("/sse", func(c *gin.Context) {
		// 设置 SSE 相关 Header
		c.Writer.Header().Set("Content-Type", "text/event-stream")
		c.Writer.Header().Set("Cache-Control", "no-cache")
		c.Writer.Header().Set("Connection", "keep-alive")

		// 监听客户端断开连接
		notify := c.Writer.CloseNotify()

		// 模拟持续推送
		for {
			select {
			case <-notify:
				fmt.Println("客户端断开连接")
				return
			default:
				// 发送数据
				c.SSEvent("message", gin.H{"time": time.Now().Format("15:04:05")})
				c.Writer.Flush() // 立即刷新
				time.Sleep(2 * time.Second)
			}
		}
	})

	r.Run(":8080")
}

前端(Vue3 + Composition API)监听 SSE

Vue3 通过 EventSource 监听 SSE 事件。

1. Vue3 组件实现

创建 SseComponent.vue

vue 复制代码
<template>
  <div>
    <h2>SSE 推送数据</h2>
    <p v-if="message">时间:{{ message }}</p>
    <button @click="stopSSE">断开连接</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";

let eventSource = null;
const message = ref("");

const startSSE = () => {
  eventSource = new EventSource("http://localhost:8080/sse");

  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    message.value = data.time;
  };

  eventSource.onerror = () => {
    console.error("SSE 连接错误");
    eventSource.close();
  };
};

const stopSSE = () => {
  if (eventSource) {
    eventSource.close();
    console.log("SSE 连接已关闭");
  }
};

onMounted(startSSE);
onUnmounted(stopSSE);
</script>

3. 运行 Gin 服务器和 Vue 前端

启动 Gin 服务器:

sh 复制代码
go run main.go

启动 Vue3:

sh 复制代码
npm run dev

然后在浏览器访问 Vue 页面,即可看到 SSE 推送的消息不断更新。


这样,我们就完成了 Gin + Vue3 的 SSE 实时推送 ,适用于实时通知、股票行情、日志监控等场景 🎉。

相关推荐
程序员黑豆5 小时前
Java类型推断完全指南:从var到菱形运算符,掌握使用限制与最佳实践
java·前端·ai编程
To_OC5 小时前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
GreenTea5 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
浮生望6 小时前
前端API工程化:用 Mock 数据与 Axios 配置实现独立于后端的并行开发
前端
万少6 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波0076 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis7 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝8 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
计算机魔术师9 小时前
新兴多智能体系统的模式与问题
前端
用户059540174469 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css