当前位置: 首页 > article >正文

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

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

后端(Gin)实现 SSE

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

1. 安装 Gin

确保你的 Go 项目已安装 gin

go get -u github.com/gin-gonic/gin
2. Gin SSE 服务器

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

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

<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 服务器:

go run main.go

启动 Vue3:

npm run dev

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


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


http://www.kler.cn/a/587505.html

相关文章:

  • [Jenkins] 即将关闭,剩余生成将不会被执行问题解决
  • 支付宝小程序评论提升策略:打造高互动度的用户体验
  • 【NLP】 3. Distributional Similarity in NLP(分布式相似性)
  • 责任链模式如何减少模块之间的耦合
  • starrocks批量启停脚本
  • 生成对抗网络——pytorch与paddle实现生成对抗网络
  • WordPress顶部菜单自定义的方法
  • 酒店宾馆IPTV数字电视系统:创新宾客体验,引领智慧服务新潮流
  • 【蓝桥】模拟
  • Spring Boot整合RabbitMQ极简教程
  • 【小沐学Web3D】three.js 加载三维模型(React)
  • 微信小程序wx.request接口报错(errno: 600001, errMsg: “request:fail -2:net::ERR_FAILED“)
  • 有效封装一个 WebSocket 供全局使用
  • Vue 中如何实现自定义指令?
  • 《DeepSeek 开源 DeepGEMM:开启AI计算新时代的密钥》:此文为AI自动生成
  • 变量赋值汇编
  • 【C】嵌入式的中断,理解
  • Modbus TCP到RTU:轻松转换指南!
  • docker mysql 默认配置文件路径
  • 架构思维:软件建模与架构设计的关键要点