Implementing Events via HTTP

For some tasks that require real-time data updates, such as news feeds, notifications, or chat streams, we can do without complex two-way protocols like WebSocket. We can use a simple mechanism for transferring data from the server to the client via HTTP, which is often more convenient and efficient to configure for one-way data exchange.

How does this work?

The client opens a persistent HTTP connection to the server. The server periodically sends data as it is updated in text format, which the client can receive and display in real time. The client connection remains open, and the server continues to send updates until the connection is closed. Please note that this uses one HTTP connection.which simplifies implementation and reduces the load on the server, since there is no need to constantly open new connections for each data transfer.

Example of implementation in Python

Below is an example of a simple Flask server that sends updates to the client every second:

from flask import Flask, Response
import time

app = Flask(__name__)

# Генератор событий
def event_stream():
    while True:
        time.sleep(1)
        yield f"data: {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n"

@app.route('/stream')
def stream():
    return Response(event_stream(), mimetype="text/event-stream")

if __name__ == '__main__':
    app.run(debug=True)

This code sends messages to the client every few seconds. The main advantage here is that it does not require complex setup or additional libraries for two-way communication.

Example of the client part

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Event Stream</title>
</head>
<body>
    <h1>Сообщения от сервера:</h1>
    <pre id="log"></pre>

    <script>
        const eventSource = new EventSource("/stream");
        eventSource.onmessage = function(event) {
            document.getElementById('log').innerText += event.data + "\n";
        };
    </script>
</body>
</html>

Client side via object EventSource receives messages and displays them on the screen. This is a simple way to organize real-time updates without using more complex protocols.

Features and limitations

  • The mechanism works on top of HTTP, which makes it easy to integrate into existing systems.

  • Automatic reconnection: if the connection is lost, the browser will try to reconnect automatically.

  • Limitation: The approach is not designed for two-way communication and has a limit on the number of connections from one client (usually up to 6 connections per domain).

Thus, if the task comes down to regularly updating data from the server, then this method may prove to be a convenient and easy-to-implement solution.

Client implementation in Python

In addition to the JavaScript example, you can consider implementing a client in Python that will receive events via HTTP. For this, you can use the library sseclientwhich simplifies working with Server-Sent Events.

import sseclient
import requests

def event_stream(url):
    response = requests.get(url, stream=True)
    client = sseclient.SSEClient(response)

    for event in client.events():
        print(f'Received event: {event.data}')

if __name__ == '__main__':
    event_stream('http://localhost:5000/stream')

Here:

  • Library is used requests to send a GET request to the server with a flag stream=Truewhich allows you to process events in real time.

  • sseclient.SSEClient connects to the event stream sent by the server.

  • In a cycle for The data for each received event is displayed.

This code can be useful if you need to receive and process real-time events on a client written in Python. For example, this can be useful for server applications that need to respond to updates from other servers or systems.

If the task requires simple and reliable data transfer from the server to the client, this approach may be a good choice. In case of two-way exchange or work with binary data, it may be worth considering WebSocket or other technologies.

Depending on the specific requirements of your application, choosing between different technologies may depend on ease of implementation, scalability, and supported features.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *