Home Backend Development Python Tutorial Implementing Server-Sent Events (SSE) with Python and Go

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

Dec 22, 2024 am 08:35 AM

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
Copy after login

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)
Copy after login

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)
    }
}
Copy after login

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.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example ?</title>
</head>
<body>
    <h1>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/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173482771419125.jpg" 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/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173482771591634.jpg" class="lazy" alt="Implementing Server-Sent Events (SSE) with Python and Go"></p>


          

            
        
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

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...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

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 does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles