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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function