Junior — Middle
Can you explain what Server-Sent Events are and how they work?
sobes.tech AI
Answer from AI
Server-Sent Events (SSE) is a technology that allows a server to send updates to a client in real-time over a unidirectional HTTP connection. The client establishes a connection with the server, and the server can send a stream of data over this connection, such as status updates or events.
How it works:
- The client sends an HTTP request with the header
Accept: text/event-stream. - The server responds with the content type
text/event-streamand starts sending data in event format. - Each event consists of multiple lines, for example,
data: messageand an empty line indicating the end of the event. - The connection remains open, and the server can send new events as they occur.
Example of a simple SSE server in Python using Flask:
from flask import Flask, Response
import time
app = Flask(__name__)
def event_stream():
count = 0
while True:
yield f"data: Message {count}\n\n"
count += 1
time.sleep(1)
@app.route('/stream')
def stream():
return Response(event_stream(), mimetype='text/event-stream')
if __name__ == '__main__':
app.run(debug=True, threaded=True)
The client can connect to /stream and receive updates in real-time.