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.
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.
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.
SSE enables the server to push messages to the browser in real-time. As part of the HTML5 specification, it involves:
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 |
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).
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).
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)
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) } }
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="https://img.php.cn/upload/article/000/000/000/173482771419125.jpg" 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="https://img.php.cn/upload/article/000/000/000/173482771591634.jpg" alt="Implementing Server-Sent Events (SSE) with Python and Go"></p>
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!