With server-sent events, it’s possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.
Преимущества
- Простота использования. Данные идут только от сервера к клиенту, что упрощает логику и сервера, и клиента.
- Поддерживается всеми основными браузерами.
Особенности и недостатки
- Так как каждый клиент имеет отдельное соединение с сервером, нет возможности разослать одновременно одно и то же сообщение с сервера всем подключенным клиентам (broadcast).
- Это очевидно, но тем не менее – нет возможности отправлять данные с клиента на сервер.
Events
Each message consists of one or more lines of text listing the fields for that message. Each field is represented by the field name, followed by a colon, followed by the text data for that field’s value.
Each message received has some combination of the following fields, one per line:
-
event
: A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should useaddEventListener()
to listen for named events. Theonmessage
handler is called if no event name is specified for a message. -
data
: The data field for the message. When theEventSource
receives multiple consecutive lines that begin withdata:
, it concatenates them, inserting a newline character between each one. Trailing newlines are removed. -
id
: The event ID to set theEventSource
object’s last event ID value. -
retry
: The reconnection time. If the connection to the server is lost, the browser will wait for the specified time before attempting to reconnect. This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
All other field names are ignored.
Примеры
Server
Client
References
- https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events
- https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
📂 Web | Последнее изменение: 09.01.2025 22:09