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 实时推送 ,适用于实时通知、股票行情、日志监控等场景 🎉。

相关推荐
刮涂层_赢大奖10 分钟前
我把 AI 编程 Agent 变成了宝可梦,让它们在像素风办公室里跑来跑去
前端·typescript·claude
重庆穿山甲1 小时前
Java开发者的大模型入门:Spring AI组件全攻略(二)
前端·后端
重庆穿山甲1 小时前
Java开发者的大模型入门:Spring AI组件全攻略(一)
前端·后端
布列瑟农的星空1 小时前
前端都能看懂的rust入门教程(二)——函数和闭包
前端·后端·rust
晨米酱2 小时前
四、Prettier 编辑器集成指南
前端·代码规范
文心快码BaiduComate2 小时前
Comate 4.0新年全面焕新!底层重构、七大升级、复杂任务驾驭力跃升
前端·程序员·架构
怪可爱的地球人2 小时前
uni-app:5 步接入 vite-plugin-uni-pages,用 <route> 自动生成 pages.json
前端
前端Hardy2 小时前
告别 !important:现代 CSS 层叠控制指南,90% 的样式冲突其实不用它也能解
前端·vue.js·面试
前端Hardy2 小时前
Vue 3 性能优化的 5 个隐藏技巧,第 4 个连老手都未必知道
前端·vue.js·面试
炫饭第一名2 小时前
速通Canvas指北🦮——路径与形状篇
前端·javascript·程序员