SSE最简单的demo(服务器发送事件)
介绍
服务器发送事件 (SSE) 是一种 Web 技术,允许服务器通过 HTTP 将实时更新推送到客户端。与 WebSocket 不同,SSE 实现起来更简单,因为它使用从服务器到浏览器的单向通信通道,并通过常规 HTTP 连接工作。它对于需要定期更新的应用程序特别有用,例如实时比分、通知或实时监控仪表板。
我创建了这个演示,因为我目前正在开发一个应用程序,人工智能可以在其中讨论各种主题。我想实现一些类似流的功能,并发现了名为“SSE”的技术。
演示概述
此演示展示了如何使用服务器发送事件 (SSE) 将实时更新从 API 发送到浏览器。在此示例中,浏览器显示服务器发送的一系列示例消息。该演示的简单性使其成为了解 SSE 如何工作并将其集成到您的项目中的绝佳起点。
演示视频
下面的视频演示了服务器发送事件 (SSE) 演示如何实时工作。观看此视频将使您更好地了解客户端和服务器如何交互以提供实时更新。
执行
服务器发送事件(SSE)演示的核心实现分为两部分:前端和后端。完整的源代码可在 GitHub 上找到:sse-demo 存储库。
前端 (ui/src/app/page.tsx)
前端使用 React 构建,提供启动和停止 SSE 连接的按钮,显示来自服务器的实时消息。主要亮点如下:
-
连接到 SSE:handleStartConnection 函数创建一个连接到 /events 端点的 EventSource 对象。它监听消息、打开事件和错误事件:
- onmessage:处理传入消息并更新消息状态。
- onopen:建立连接时记录。
- onerror:处理错误、记录详细信息并在需要时关闭连接。
停止连接:handleStopConnection函数关闭SSE连接并进行清理。
UI:该页面包括一个简单的界面,带有开始/停止按钮和一个显示消息的列表。
"use client"; import type React from "react"; import { useState } from "react"; const App: React.FC = () => { const [messages, setMessages] = useState<string[]>([]); const [eventSource, setEventSource] = useState<EventSource | null>(null); const handleStartConnection = () => { const newEventSource = new EventSource("http://localhost:8080/events"); const handleOnMessage = (event: MessageEvent) => { console.log("onmessage", event.data); setMessages((prev) => [...prev, event.data]); }; const handleOnOpen = () => { console.log("Connection established"); }; const handleOnError = (error: Event) => { console.error("onerror", error); console.log("readyState:", newEventSource.readyState); console.log("Connection error occurred."); newEventSource.close(); setEventSource(null); }; const handleOnClose = () => { console.log("Connection is being closed by the server."); newEventSource.close(); setEventSource(null); }; newEventSource.onmessage = handleOnMessage; newEventSource.onopen = handleOnOpen; newEventSource.onerror = handleOnError; newEventSource.addEventListener("close", handleOnClose); setEventSource(newEventSource); }; const handleStopConnection = () => { if (eventSource) { eventSource.close(); setEventSource(null); console.log("Connection closed"); } }; return ( <div> <h1>Server-Sent Events Demo</h1> <button type="button" onClick={handleStartConnection} disabled={!!eventSource} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50" > Start Connection </button> <button type="button" onClick={handleStopConnection} disabled={!eventSource} className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50 ml-2" > Stop Connection </button> <ul> {messages.map((message, index) => ( <li key={`${index}-${message}`}>{message}</li> ))} </ul> </div> ); }; export default App;
后端(api/main.go)
后端是使用 Go 的 Gin 框架构建的,包括以下主要功能:
CORS 配置:后端使用 Gin CORS 中间件来允许调试期间的连接。
-
SSE 端点:/events 端点将一系列预定义消息流式传输到客户端,每条消息之间存在延迟。关键组件:
- 标头设置为指定文本/事件流内容类型。
- 消息循环发送,每条消息之间有 2 秒的延迟。
- 最终关闭事件标志着连接的结束。
"use client"; import type React from "react"; import { useState } from "react"; const App: React.FC = () => { const [messages, setMessages] = useState<string[]>([]); const [eventSource, setEventSource] = useState<EventSource | null>(null); const handleStartConnection = () => { const newEventSource = new EventSource("http://localhost:8080/events"); const handleOnMessage = (event: MessageEvent) => { console.log("onmessage", event.data); setMessages((prev) => [...prev, event.data]); }; const handleOnOpen = () => { console.log("Connection established"); }; const handleOnError = (error: Event) => { console.error("onerror", error); console.log("readyState:", newEventSource.readyState); console.log("Connection error occurred."); newEventSource.close(); setEventSource(null); }; const handleOnClose = () => { console.log("Connection is being closed by the server."); newEventSource.close(); setEventSource(null); }; newEventSource.onmessage = handleOnMessage; newEventSource.onopen = handleOnOpen; newEventSource.onerror = handleOnError; newEventSource.addEventListener("close", handleOnClose); setEventSource(newEventSource); }; const handleStopConnection = () => { if (eventSource) { eventSource.close(); setEventSource(null); console.log("Connection closed"); } }; return ( <div> <h1>Server-Sent Events Demo</h1> <button type="button" onClick={handleStartConnection} disabled={!!eventSource} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50" > Start Connection </button> <button type="button" onClick={handleStopConnection} disabled={!eventSource} className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50 ml-2" > Stop Connection </button> <ul> {messages.map((message, index) => ( <li key={`${index}-${message}`}>{message}</li> ))} </ul> </div> ); }; export default App;
如何运行它
要运行此演示,请参阅 GitHub 存储库中的 README.md 文件。它包含设置和运行项目前端和后端的分步说明。
结论
此演示提供了对服务器发送事件 (SSE) 的简单而有效的介绍,演示了如何将实时消息从服务器流式传输到浏览器。通过关注基础知识,它旨在帮助您快速理解核心概念并开始在自己的项目中尝试 SSE。
如果您有兴趣尝试或基于此示例进行构建,请查看 GitHub 上的完整源代码:sse-demo 存储库。
以上是SSE最简单的demo(服务器发送事件)的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Go语言在构建高效且可扩展的系统中表现出色,其优势包括:1.高性能:编译成机器码,运行速度快;2.并发编程:通过goroutines和channels简化多任务处理;3.简洁性:语法简洁,降低学习和维护成本;4.跨平台:支持跨平台编译,方便部署。

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

GoimpactsdevelopmentPositationalityThroughSpeed,效率和模拟性。1)速度:gocompilesquicklyandrunseff,ifealforlargeprojects.2)效率:效率:ITScomprehenSevestAndArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增强开发的简单性:3)SimpleflovelmentIcties:3)简单性。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。

C 更适合需要直接控制硬件资源和高性能优化的场景,而Golang更适合需要快速开发和高并发处理的场景。1.C 的优势在于其接近硬件的特性和高度的优化能力,适合游戏开发等高性能需求。2.Golang的优势在于其简洁的语法和天然的并发支持,适合高并发服务开发。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。
