Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
e3ffff5
Update article.md
astropsy999 May 24, 2022
ceb3946
Update article.md
astropsy999 May 24, 2022
f6aafd1
Update article.md
astropsy999 May 25, 2022
0f3f2a9
Update article.md
astropsy999 May 25, 2022
ba4c2b9
Update article.md
astropsy999 May 25, 2022
9a855d9
Update article.md
astropsy999 May 26, 2022
ca0b538
Update article.md
astropsy999 May 26, 2022
52e5ab9
Update article.md
astropsy999 May 26, 2022
7d621a6
Update article.md
astropsy999 May 26, 2022
b310810
Update index.html
astropsy999 May 26, 2022
46d37a3
Update article.md
astropsy999 Jun 4, 2022
d5d59f6
Update article.md
astropsy999 Jun 4, 2022
3fe04de
Update article.md
astropsy999 Jun 5, 2022
d161dd1
Update index.html
astropsy999 Jun 5, 2022
52bf3af
Update article.md
astropsy999 Jun 5, 2022
8f3e3fe
Update article.md
astropsy999 Jun 6, 2022
ac9996b
Update article.md
astropsy999 Jun 6, 2022
3bd140e
Update article.md
astropsy999 Jun 7, 2022
18a38a3
Update iframe.html
astropsy999 Jun 7, 2022
75d1f7c
Update index.html
astropsy999 Jun 7, 2022
d9660ab
Update iframe.html
astropsy999 Jun 7, 2022
fb08989
Update facebook.html
astropsy999 Jun 7, 2022
0ef68a9
Update index.html
astropsy999 Jun 7, 2022
6e53413
Update facebook.html
astropsy999 Jun 7, 2022
c80ed0f
Update index.html
astropsy999 Jun 7, 2022
469e2d3
Update article.md
astropsy999 Jun 8, 2022
f84fa7d
Merge branch 'master' into master
astropsy999 Jun 8, 2022
d4c6a64
Update article.md
astropsy999 Jun 8, 2022
935199a
Update article.md
astropsy999 Jun 9, 2022
5f35c46
Update article.md
astropsy999 Jun 10, 2022
999ab9d
Update task.md
astropsy999 Jun 12, 2022
fafe785
Update task.md
astropsy999 Jun 12, 2022
76007bc
Update index.html
astropsy999 Jun 12, 2022
84362d4
Update index.html
astropsy999 Jun 12, 2022
22fdad6
Update index.html
astropsy999 Jun 12, 2022
d051d1e
Update index.html
astropsy999 Jun 12, 2022
f0f4d93
Update index.html
astropsy999 Jun 12, 2022
58e0228
Update index.html
astropsy999 Jun 12, 2022
d3cdbac
Update index.html
astropsy999 Jun 12, 2022
410a0e1
Update index.html
astropsy999 Jun 12, 2022
18f9da2
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
a6806c0
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
82cd9d5
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
6b1b439
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
64ccba1
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
e2a2219
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
ab9ef8d
Update 3-frames-and-windows/06-clickjacking/article.md
astropsy999 Jul 3, 2022
af25da9
Update 3-frames-and-windows/06-clickjacking/clickjacking-visible.view…
astropsy999 Jul 3, 2022
3a10141
Update 3-frames-and-windows/06-clickjacking/clickjacking-visible.view…
astropsy999 Jul 3, 2022
08ed6b1
Update 3-frames-and-windows/06-clickjacking/clickjacking.view/index.html
astropsy999 Jul 3, 2022
74de077
Apply suggestions from code review
dolgachio Jul 12, 2022
494b88d
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 21, 2022
f3db6f5
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 21, 2022
afeb15b
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 21, 2022
10e610c
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 21, 2022
5d29d2d
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 21, 2022
118c6cf
Update 7-animation/2-css-animations/article.md
astropsy999 Jul 21, 2022
c0b84c4
Update 7-animation/2-css-animations/article.md
astropsy999 Jul 21, 2022
ab8be27
Update 7-animation/2-css-animations/article.md
astropsy999 Jul 21, 2022
5ae6e12
Update 7-animation/2-css-animations/article.md
astropsy999 Jul 21, 2022
d2973b3
Update 7-animation/2-css-animations/article.md
astropsy999 Jul 21, 2022
1da1d54
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 28, 2022
2078a03
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 28, 2022
9a56401
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 28, 2022
400fbf6
Update 5-network/12-server-sent-events/article.md
astropsy999 Jul 28, 2022
51a327f
Update 6-data-storage/03-indexeddb/article.md
astropsy999 Jul 28, 2022
80213a9
Update 6-data-storage/03-indexeddb/article.md
astropsy999 Jul 28, 2022
51fc021
Update 6-data-storage/03-indexeddb/article.md
astropsy999 Jul 28, 2022
6529a81
Update 6-data-storage/03-indexeddb/article.md
astropsy999 Jul 28, 2022
fd843a1
Update 7-animation/2-css-animations/article.md
astropsy999 Jul 28, 2022
4e193b5
Apply suggestions from code review
dolgachio Aug 4, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update article.md
54,8%
  • Loading branch information
astropsy999 authored Jun 4, 2022
commit 46d37a347865e6693884f2e5d5c3926d92537b98
118 changes: 59 additions & 59 deletions 5-network/12-server-sent-events/article.md
Original file line number Diff line number Diff line change
@@ -1,152 +1,152 @@
# Server Sent Events

The [Server-Sent Events](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) specification describes a built-in class `EventSource`, that keeps connection with the server and allows to receive events from it.
Специфікація [Server-Sent Events](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) описує вбудований клас `EventSource`, який підтримує з’єднання з сервером і дозволяє отримувати від нього події.

Similar to `WebSocket`, the connection is persistent.
Подібно до `WebSocket`, з’єднання є постійним.

But there are several important differences:
Але є кілька важливих відмінностей:

| `WebSocket` | `EventSource` |
|-------------|---------------|
| Bi-directional: both client and server can exchange messages | One-directional: only server sends data |
| Binary and text data | Only text |
| WebSocket protocol | Regular HTTP |
| Двонаправлений: клієнт і сервер можуть обмінюватися повідомленнями | Односпрямований: дані надсилає лише сервер |
Comment thread
astropsy999 marked this conversation as resolved.
Outdated
| Двійкові та текстові дані | Тільки текст |
| WebSocket протокол | Звичайний HTTP |

`EventSource` is a less-powerful way of communicating with the server than `WebSocket`.
`EventSource` є менш потужним способом зв’язку з сервером, ніж `WebSocket`.

Why should one ever use it?
Навіщо його використовувати?

The main reason: it's simpler. In many applications, the power of `WebSocket` is a little bit too much.
Основна причина: він простіший. У багатьох програмах потужність `WebSocket` є дещо занадто великою.

We need to receive a stream of data from server: maybe chat messages or market prices, or whatever. That's what `EventSource` is good at. Also it supports auto-reconnect, something we need to implement manually with `WebSocket`. Besides, it's a plain old HTTP, not a new protocol.
Нам потрібно отримати потік даних із сервера: можливо, повідомлення в чаті чи ринкові ціни, чи що завгодно. Це те, у чому сильный `EventSource`. Також він підтримує автоматичне перепідключення, що зазвичай потрібно реалізовувати вручну за допомогою `WebSocket`. Крім того, це звичайний старий HTTP, а не новий протокол.

## Getting messages
## Отримання повідомлень

To start receiving messages, we just need to create `new EventSource(url)`.
Щоб почати отримувати повідомлення, необхідно створити `new EventSource(url)`.

The browser will connect to `url` and keep the connection open, waiting for events.
Браузер підключиться до `url` і залишить з’єднання відкритим, чекаючи на події.

The server should respond with status 200 and the header `Content-Type: text/event-stream`, then keep the connection and write messages into it in the special format, like this:
Сервер повинен відповісти статусом 200 і заголовком `Content-Type: text/event-stream`, а потім зберегти з’єднання та писати повідомлення в спеціальному форматі, наприклад:

```
data: Message 1
data: Повідомлення 1

data: Message 2
data: Повідомлення 2

data: Message 3
data: of two lines
data: Повідомлення 3
data: з двох рядків
```

- A message text goes after `data:`, the space after the colon is optional.
- Messages are delimited with double line breaks `\n\n`.
- To send a line break `\n`, we can immediately send one more `data:` (3rd message above).
- Текст повідомлення йде після `data:`, пробіл після двокрапки необов’язковий.
- Повідомлення розділені подвійними розривами рядків `\n\n`.
- Щоб надіслати розрив рядка `\n`, ми можемо негайно надіслати ще одне `data:` (3-е повідомлення вище).
Comment thread
astropsy999 marked this conversation as resolved.
Outdated

In practice, complex messages are usually sent JSON-encoded. Line-breaks are encoded as `\n` within them, so multiline `data:` messages are not necessary.
На практиці складні повідомлення зазвичай надсилаються в кодуванні JSON. Розриви рядків у них кодуються як `\n`, тому багаторядкові повідомлення `data:` не потрібні.

For instance:
Наприклад:

```js
data: {"user":"John","message":"First line*!*\n*/!* Second line"}
data: {"user":"Тарас","message":"Перший рядок*!*\n*/!* Другий рядок"}
```

...So we can assume that one `data:` holds exactly one message.
...Отже, можемо припустити, що один `data:` містить рівно одне повідомлення.

For each such message, the `message` event is generated:
Для кожного такого повідомлення генерується подія `message`:

```js
let eventSource = new EventSource("/events/subscribe");

eventSource.onmessage = function(event) {
console.log("New message", event.data);
// will log 3 times for the data stream above
console.log("Нове повідомлення", event.data);
// буде зареєстровано 3 рази для потоку даних вище
};

// or eventSource.addEventListener('message', ...)
// чи eventSource.addEventListener('message', ...)
```

### Cross-origin requests
### Запити з перехресних доменів

`EventSource` supports cross-origin requests, like `fetch` and any other networking methods. We can use any URL:
`EventSource` підтримує запити між різними джерелами, як-от `fetch` та будь-які інші мережеві методи. Ми можемо використовувати будь-яку URL-адресу:

```js
let source = new EventSource("https://another-site.com/events");
```

The remote server will get the `Origin` header and must respond with `Access-Control-Allow-Origin` to proceed.
Віддалений сервер отримає заголовок `Origin` і повинен відповісти `Access-Control-Allow-Origin` , щоб продовжити.

To pass credentials, we should set the additional option `withCredentials`, like this:
Щоб передати облікові дані, ми повинні встановити додатковий параметр `withCredentials`, наприклад:

```js
let source = new EventSource("https://another-site.com/events", {
withCredentials: true
});
```

Please see the chapter <info:fetch-crossorigin> for more details about cross-origin headers.
Будь ласка, перегляньте розділ <info:fetch-crossorigin>, щоб дізнатися більше про заголовки з перехресними джерелами.


## Reconnection
## Повторне з’єднання

Upon creation, `new EventSource` connects to the server, and if the connection is broken -- reconnects.
Після створення `new EventSource` підключається до сервера, і якщо з’єднання розривається - автоматично підключається знову.

That's very convenient, as we don't have to care about it.
Це дуже зручно, оскільки не потрібно дбати про це.
Comment thread
astropsy999 marked this conversation as resolved.
Outdated

There's a small delay between reconnections, a few seconds by default.
Між повторними з’єднаннями є невелика затримка, за замовчуванням кілька секунд.

The server can set the recommended delay using `retry:` in response (in milliseconds):
Сервер може встановити рекомендовану затримку, використовуючи `retry:` у відповідь (у мілісекундах):

```js
retry: 15000
data: Hello, I set the reconnection delay to 15 seconds
data: Привіт, я встановив затримку повторного з’єднання на 15 секунд
```

The `retry:` may come both together with some data, or as a standalone message.
`retry:` може надсилатись як разом із деякими даними, так і окремим повідомленням.

The browser should wait that many milliseconds before reconnecting. Or longer, e.g. if the browser knows (from OS) that there's no network connection at the moment, it may wait until the connection appears, and then retry.
Браузер повинен зачекати вказану кількість мілісекунд перед повторним з’єднанням. Або довше, напр. якщо браузер знає (з ОС), що на даний момент немає підключення до мережі, він може зачекати, доки з’єднання з’явиться, а потім повторити спробу.

- If the server wants the browser to stop reconnecting, it should respond with HTTP status 204.
- If the browser wants to close the connection, it should call `eventSource.close()`:
- Якщо сервер бажає, щоб браузер припинив повторне з’єднання, він повинен відповісти HTTP статусом 204.
- Якщо браузер хоче закрити з’єднання, він повинен викликати `eventSource.close()`:

```js
let eventSource = new EventSource(...);

eventSource.close();
```

Also, there will be no reconnection if the response has an incorrect `Content-Type` or its HTTP status differs from 301, 307, 200 and 204. In such cases the `"error"` event will be emitted, and the browser won't reconnect.
Крім того, не буде повторного з’єднання, якщо відповідь містить неправильний `Content-Type` або його статус HTTP відрізняється від 301, 307, 200 і 204. У таких випадках буде створено подію `"помилка"`, і браузер не підключатиметься повторно.

```smart
When a connection is finally closed, there's no way to "reopen" it. If we'd like to connect again, just create a new `EventSource`.
Коли з’єднання остаточно закрито, його неможливо «відкрити» знову. Якщо ми хочемо знову під’єднатися, доведеться створити новий `EventSource`.
Comment thread
astropsy999 marked this conversation as resolved.
Outdated
```

## Message id
## Ідентифікатор повідомлення

When a connection breaks due to network problems, either side can't be sure which messages were received, and which weren't.
Коли з’єднання розривається через проблеми з мережею, жодна сторона не може бути впевнена, які повідомлення були отримані, а які ні.

To correctly resume the connection, each message should have an `id` field, like this:
Щоб правильно відновити з’єднання, кожне повідомлення має мати поле `id`, наприклад:

```
data: Message 1
data: Повідомлення 1
id: 1

data: Message 2
data: Повідомлення 2
id: 2

data: Message 3
data: of two lines
data: Повідомлення 3
data: з двох рядків
id: 3
```

When a message with `id:` is received, the browser:
Коли повідомлення з `id:` отримане браузером:
Comment thread
astropsy999 marked this conversation as resolved.
Outdated

- Sets the property `eventSource.lastEventId` to its value.
- Upon reconnection sends the header `Last-Event-ID` with that `id`, so that the server may re-send following messages.
- Встановлюється значення властивості `eventSource.lastEventId`.
- Після повторного підключення надсилається заголовок `Last-Event-ID` з цим `id`, щоб сервер міг повторно надіслати наступні повідомлення.

```smart header="Put `id:` after `data:`"
Please note: the `id` is appended below message `data` by the server, to ensure that `lastEventId` is updated after the message is received.
```smart header="Зазначайте `id:` після `data:`"
Зверніть увагу: `id` додається сервером під повідомленням `data` , щоб гарантувати, що `lastEventId` оновлюється після отримання повідомлення.
```

## Connection status: readyState
## Статус підключення: readyState

The `EventSource` object has `readyState` property, that has one of three values:

Expand Down