Anton Sidorov homepage

Bookmark this to keep an eye on my project updates!

Follow me on GitHub

Server Sent Events

Зачем

Реализует однонаправленную связь в паттернах интеграции.

Server Sent Events (Server-Side Events):

Плюсы-минусы

Плюсы:

  • automatic reconnection,
  • event IDs
  • automatic event parsing

Минусы:

  • Ограничение, связанное с количеством соединений, которые могут быть открыты между клиентом и сервером одновременно
  • Поддержка 97,5% браузеров в 2023 году, но IE<11 нет, Edge только
  • It only allows data reception from the server (unidirectional)
  • Events are limited to UTF-8 (no binary data)
  • Limitations on connecting from one browser at a time:
    • HTTP/1.1: Max 6-8 connections at a time.
    • HTTP/2: Max 100 connections by default (can be changed from server configuration).

Модель

Модель:

  • data - JSON
  • event - Event Name - Client subscribe to type of events
    • default генерирует 3 события:
      • message – получено сообщение, доступно как event.data.
      • open – соединение открыто.
      • error – не удалось установить соединение, например, сервер вернул статус 500
  • lastEventId - ИД события
  • retry - мс на переподключение при обрыве связи

Patterns

  • Адресация сообщений возможна по event
    • пример: ИДПользователя_ДоговорСтатусИзменен, где клиент подписывается на события для конкретного пользователя, сервер ИД пользователя получает при аутентификации.
  • Обработка потери соединения
    • Setting an ID lets the browser keep track of the last event fired so that if, the connection to the server is dropped, a special HTTP header (Last-Event-ID) is set with the new request. This lets the browser determine which event is appropriate to fire. The message event contains a e.lastEventId property. server can implement several different strategies:
    • If lost messages are acceptable, then no event IDs or special logic is required: simply let the client reconnect and resume the stream.
    • If message recovery is required, then the server needs to specify IDs for relevant events, such that the client can report the last seen ID when reconnecting.
    • Also, the server needs to implement some form of a local cache to recover and retransmit missed messages to the client. . - варианты реализации на сервере получить сообщения после last-event-id: Redis Streams

Технологии