search
HomeBackend DevelopmentPython TutorialImplementing Server-Sent Events (SSE) with Python and Go

In today's interactive web applications, real-time data updates are crucial in enhancing user experiences. Among various real-time communication technologies, Server-Sent Events (SSE) stand out as a simple yet effective solution. SSE allows servers to push real-time updates to clients over HTTP.

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

What is SSE?

Server-Sent Events (SSE) is a technology used to enable the server to push data to the client proactively, also known as "Event Stream." It is based on the HTTP protocol and takes advantage of its long-lived connection characteristics. SSE establishes a persistent connection between the client and the server, allowing the server to send real-time data updates to the client. However, the client cannot send data back to the server through SSE.

Why Choose SSE?

Server-Sent Events are part of the HTML5 specification, specifically designed for pushing events from the server to the client. Its simplicity, automatic reconnection, and event tracking features make it ideal for scenarios requiring a unidirectional data flow. SSE performs exceptionally well when data is streamed in one direction.

Overview

SSE enables the server to push messages to the browser in real-time. As part of the HTML5 specification, it involves:

  • Communication Protocol: Utilizes HTTP.
  • Event Objects: Available on the browser side.

While WebSockets also offer real-time communication, they differ significantly:

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

Server Implementation

Protocol Implementation

Essentially, the browser initiates an HTTP request, and the server responds with an HTTP status along with these headers:

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

SSE specifies that the MIME type for event streams must be text/event-stream. Browsers should not cache data, and connections should remain persistent (keep-alive).

Message Format

Event streams use UTF-8 encoded text or Base64 encoded binary messages compressed with gzip. Each message consists of one or more fields, formatted as field-name : field-value. Each field ends with a n. Lines starting with a colon are comments, ignored by the browser. Multiple messages in a push are separated by empty lines (nn).

Key fields include:

  • event: The event type.
  • id: The event ID used by the browser to track the last received event for reconnection.
  • retry: The waiting time (in ms) for the browser to retry connection after a failure.
  • data: The message data.

Example: SSE with Python

Here's an implementation using 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)

Example: SSE with Go

Here's an implementation using 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)
    }
}

Browser API

On the client side, JavaScript's EventSource API allows you to create an EventSource object to listen to server-sent events. Once connected, the server can send event messages to the browser. The browser handles these messages by listening to onmessage, onopen, and onerror events.



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example ?</title>


    <h1 id="Server-Sent-Events-Example">Server-Sent Events Example ?</h1>
    <div>



<h2>
  
  
  SSE Debugging Tools
</h2>

<p>Currently, many popular tools like Postman, Insomnia, Bruno, and ThunderClient lack adequate support for debugging Server-Sent Events (SSE). This limitation can be quite frustrating during development. Fortunately, EchoAPI provides excellent SSE debugging capabilities, greatly improving workflow efficiency and productivity.</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173482771419125.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Implementing Server-Sent Events (SSE) with Python and Go"></p>

<p>If you're working with SSE or API debugging, I highly recommend trying EchoAPI. It can revolutionize your debugging experience and streamline your development process. For more information, visit echoapi.com. </p>
<h3>
  
  
  Example: EchoAPI Client for SSE
</h3>

<p>In EchoAPI, using the SSE interface is straightforward. Simply enter the URL, fill in the relevant parameters, and click "<strong>Send</strong>" to view your request results.</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173482771591634.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Implementing Server-Sent Events (SSE) with Python and Go"></p>


          </div>

            
        

The above is the detailed content of Implementing Server-Sent Events (SSE) with Python and Go. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop?How to use regular expression to match the first closed tag and stop?Apr 02, 2025 am 07:06 AM

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor