首页 > 后端开发 > Python教程 > 使用 Python 和 Go 实现服务器发送事件 (SSE)

使用 Python 和 Go 实现服务器发送事件 (SSE)

Susan Sarandon
发布: 2024-12-22 08:35:10
原创
270 人浏览过

在当今的交互式 Web 应用程序中,实时数据更新对于增强用户体验至关重要。在各种实时通信技术中,服务器发送事件 (SSE) 作为一种简单而有效的解决方案脱颖而出。 SSE 允许服务器通过 HTTP 向客户端推送实时更新。

Implementing Server-Sent Events (SSE) with Python and Go

什么是上交所?

服务器发送事件(SSE)是一种用于使服务器主动向客户端推送数据的技术,也称为“事件流”。它基于 HTTP 协议并利用其长寿命连接特性。 SSE在客户端和服务器之间建立持久连接,允许服务器向客户端发送实时数据更新。但是,客户端无法通过 SSE 将数据发送回服务器。

为什么选择上交所?

服务器发送事件是 HTML5 规范的一部分,专门用于将事件从服务器推送到客户端。其简单性、自动重连和事件跟踪功能使其非常适合需要单向数据流的场景。当数据沿一个方向流动时,SSE 表现得非常好。

概述

SSE使服务器能够实时向浏览器推送消息。作为 HTML5 规范的一部分,它涉及:

  • 通信协议:使用HTTP。
  • 事件对象:在浏览器端可用。

虽然 WebSocket 也提供实时通信,但它们之间存在显着差异:

Feature SSE WebSockets
Protocol Basis HTTP TCP
Data Flow Unidirectional (server to client) Full-duplex (bidirectional)
Complexity Lightweight and simple More complex
Reconnection Built-in Manual implementation needed
Message Tracking Automatic Manual implementation needed
Data Types Text or Base64-encoded binary Various data types supported
Event Types Support Custom events supported Custom events not supported
Limitations HTTP/1.1 or HTTP/2 Unlimited connections

服务器实现

协议实施

本质上,浏览器发起一个 HTTP 请求,服务器响应 HTTP 状态以及这些标头:

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
登录后复制

SSE 指定事件流的 MIME 类型必须是 text/event-stream。浏览器不应缓存数据,并且连接应保持持久(保持活动状态)。

消息格式

事件流使用 UTF-8 编码文本或使用 gzip 压缩的 Base64 编码二进制消息。每条消息由一个或多个字段组成,格式为字段名称:字段值。每个字段以 n 结尾。以冒号开头的行是注释,会被浏览器忽略。推送中的多条消息由空行 (nn) 分隔。

关键领域包括:

  • 事件: 事件类型。
  • id: 浏览器用于跟踪上次接收的重新连接事件的事件 ID。
  • 重试: 浏览器在失败后重试连接的等待时间(以毫秒为单位)。
  • 数据:消息数据。

示例:使用 Python 进行 SSE

这是使用 Python 的实现:

from flask import Flask, Response

app = Flask(__name__)

@app.route('/events')
def sse_handler():
    def generate():
        paragraph = [
            "Hello, this is an example of a continuous text output.",
            "It contains multiple sentences, each of which will be sent to the client as an event.",
            "This is to simulate the functionality of Server-Sent Events (SSE).",
            "We can use this method to push real-time updates.",
            "End of sample text, thank you!",
        ]

        for sentence in paragraph:
            yield f"data: {sentence}\n\n"

            import time
            time.sleep(1)

    return Response(generate(), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8081, debug=True)
登录后复制

示例:SSE 与 Go

这是使用 Go 的实现:

package main

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

func main() {
    http.HandleFunc("/events", sseHandler)

    fmt.Println("Starting server on :8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatalf("Server error: %v", err)
    }
}

func sseHandler(w http.ResponseWriter, r *http.Request) {
    flusher, ok := w.(http.Flusher)
    if !ok {
        http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    paragraph := []string{
        "Hello, this is an example of a continuous text output.",
        "It contains multiple sentences, each of which will be sent to the client as an event.",
        "This is to simulate the functionality of Server-Sent Events (SSE).",
        "We can use this method to push real-time updates.",
        "End of sample text, thank you!",
    }

    for _, sentence := range paragraph {
        _, err := fmt.Fprintf(w, "data: %s\n\n", sentence)
        if err != nil {
            return
        }
        flusher.Flush()
        time.Sleep(1 * time.Second)
    }
}
登录后复制

浏览器API

在客户端,JavaScript 的 EventSource API 允许您创建 EventSource 对象来侦听服务器发送的事件。连接后,服务器可以向浏览器发送事件消息。浏览器通过监听 onmessage、onopen 和 onerror 事件来处理这些消息。

<html lang="zh-cn">

    
    
    <title>SSE 示例?</title>
</头>

    <h1>服务器发送的事件示例?</h1>
    <div>



<h2>
  
  
  SSE调试工具
</h2>

<p>目前,许多流行的工具(例如 Postman、Insomnia、Bruno 和 ThunderClient)缺乏对调试服务器发送事件(SSE)的足够支持。在开发过程中,这种限制可能会让人非常沮丧。幸运的是,EchoAPI 提供了优秀的 SSE 调试能力,大大提高了工作流程效率和生产力。</p>

<p><img src="https://img.php.cn/upload/article/000/000/000/173482771419125.jpg" alt="Implementing Server-Sent Events (SSE) with Python and Go"></p>

<p>如果您正在使用 SSE 或 API 调试,我强烈建议您尝试 EchoAPI。它可以彻底改变您的调试体验并简化您的开发过程。欲了解更多信息,请访问 echoapi.com。 </p>
<h3>
  
  
  示例:SSE 的 EchoAPI 客户端
</h3>

<p>在 EchoAPI 中,使用 SSE 接口非常简单。只需输入网址,填写相关参数,然后点击“<strong>发送</strong>”即可查看您的请求结果。</p>

<p><img src="https://img.php.cn/upload/article/000/000/000/173482771591634.jpg" alt="Implementing Server-Sent Events (SSE) with Python and Go"></p>


          </div>

            
        
登录后复制

以上是使用 Python 和 Go 实现服务器发送事件 (SSE)的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板