Событийно-ориентированное программирование (SSE)

Давайте опубликуем текст на сайте, используя HTML теги и подсветку кода с помощью highlight.js.

Server-Sent Events (SSE)

SSE (Server-Sent Events) is one of the approaches to implementing web streaming, allowing the server to initiate the sending of information to the client side in real-time. This is particularly useful in situations where it is necessary to send data updates without requiring a client-side re-request.

To use SSE, you will need both client-side and server-side components. Let's take a look at an example of client-side code written in JavaScript:


const eventSource = new EventSource('/sse-endpoint');

eventSource.onmessage = function(event) {
  console.log('Received data: ' + event.data);
};

eventSource.onerror = function(event) {
  console.error('Error occurred: ' + event.target.readyState);
};

The above code establishes a connection with the server at the specified path '/sse-endpoint' using the EventSource object. It then sets an onmessage event handler to process the data received from the server, and an onerror event handler to handle possible errors.

Now let's turn to the server-side component. Let's consider an example of implementing SSE using the Node.js programming language and its Express framework:


const express = require('express');
const app = express();

app.get('/sse-endpoint', function(req, res) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  // Example of sending data to the client every 5 seconds
  setInterval(function() {
    const data = 'Sample data from server';
    res.write(`data: ${data}\n\n`);
  }, 5000);

  // Handling the closing of the connection from the client side
  req.on('close', function() {
    // Cleaning up resources and canceling scheduled events
    clearTimeout(intervalId);
    res.end();
  });
});

app.listen(3000, function() {
  console.log('Server running on port 3000');
});

In this example, we create an endpoint '/sse-endpoint' which sets the necessary headers and initiates sending data to the client every 5 seconds. Here, we simulate receiving data from the server at a certain interval, but in reality, the data could be obtained from a real source, such as a database or an external API.

Thus, using SSE, we can implement streaming data transmission from the server to the client, ensuring the freshness of the information and reducing latency. This is especially useful for real-time updating of the user interface, such as in chats, notification systems, or event monitoring.

Похожие вопросы на: "sse "

Скачать файлы с помощью wget
Тернарный оператор: примеры, синтаксис и особенности
Массивы в Python: основные принципы и примеры
Char Java - работа с символами в Java
Пиксели: размер, использование и преимущества
Как отключить Hyper-V: полное руководство для пользователей
Страница верхнего уровня: Page Top
Unix время: полезная информация и инструменты
Разработка на языке C в среде Eclipse: инструменты и руководство
Поиск в массиве на JavaScript: методы и примеры кода