You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
3
+
La specifica [Server-Sent Events](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface)descrive una classe built-in `EventSource`, che mantiene la connesione con il server e permette di ricevere eventi da esso.
4
4
5
-
Similar to `WebSocket`, the connection is persistent.
5
+
In modo simile ai `WebSocket`, la connessione è persistente.
6
6
7
-
But there are several important differences:
7
+
Ci sono però delle differenze sostanziali:
8
8
9
9
|`WebSocket`|`EventSource`|
10
10
|-------------|---------------|
11
11
| Bi-directional: both client and server can exchange messages | One-directional: only server sends data |
12
12
| Binary and text data | Only text |
13
13
| WebSocket protocol | Regular HTTP |
14
14
15
-
`EventSource`is a less-powerful way of communicating with the server than`WebSocket`.
15
+
`EventSource`è un modo meno potente di comunicare con il server rispetto ai`WebSocket`.
16
16
17
-
Why should one ever use it?
17
+
Perchè dovremmo usarli?
18
18
19
-
The main reason: it's simpler. In many applications, the power of`WebSocket`is a little bit too much.
19
+
La ragione principale: è semplice da usare. In molte applicazioni, la potenza dei`WebSocket`è anche troppa.
20
20
21
-
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.
21
+
Abbiamo necessità di rivcevere un data stream da un server: forse messaggi di chat o prezzi dei mercati. Quusto è ciò per cui `EventSource`è fatto. Supporta anche l'uto riconessione, qualcosa che dobbiamo invece implementare manualmente nei `WebSocket`. Oltretutto, è un normalissimo HTTP, e non un nuovo protocollo.
22
22
23
-
## Getting messages
23
+
## Ottenere i messaggi
24
24
25
-
To start receiving messages, we just need to create`new EventSource(url)`.
25
+
Per cominciare a ricevere messaggi, dobbiamo solamente creare un`new EventSource(url)`.
26
26
27
-
The browser will connect to `url` and keep the connection open, waiting for events.
27
+
Il browser si connetterà all'url e terrà la connessione aperta, in attesa di eventi.
28
28
29
-
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:
29
+
Il server dovrebbe rispondere con status 200 e l'header `Content-Type: text/event-stream`, quindi, tenere aperta la connessione e scrivere i messaggi all'interno di esso in un formato speciale come questo:
30
30
31
31
```
32
32
data: Message 1
@@ -37,94 +37,90 @@ data: Message 3
37
37
data: of two lines
38
38
```
39
39
40
-
-A message text goes after `data:`, the space after the colon is optional.
41
-
-Messages are delimited with double line breaks`\n\n`.
42
-
-To send a line break `\n`, we can immediately send one more `data:` (3rd message above).
40
+
-Un messaggio di testo che va dopo `data:`, lo spazio dopo la virgola è opzionale.
41
+
-I messaggi sono delimitati con un doppio line break`\n\n`.
42
+
-Per inviare un line break `\n`, possiamo inviare immediatamente un altro `data:` (il terzo messaggio poco più sopra).
43
43
44
-
In practice, complex messages are usually sent JSON-encoded. Line-breaks are encoded as`\n`within them, so multiline `data:`messages are not necessary.
44
+
In pratica, i messaggi complessi sono solitamente inviati tramite oggetti codificati in JSO. I Line-breaks sono codificati come`\n`tra essi, e in questo modo i messaggi `data:`multiriga non sono necessari
45
45
46
-
For instance:
46
+
Ad esempio:
47
47
48
48
```js
49
49
data: {"user":"John","message":"First line*!*\n*/!* Second line"}
50
50
```
51
51
52
-
...So we can assume that one `data:` holds exactly one message.
52
+
...In questo modo possiamo assumere che ogni `data` contenga esattamente un messaggio.
53
53
54
-
For each such message, the `message` event is generated:
54
+
Per ognuno di questi messaggi, viene generato l'evento `message`:
55
55
56
56
```js
57
57
let eventSource =newEventSource("/events/subscribe");
`EventSource`supports cross-origin requests, like`fetch`any other networking methods. We can use any URL:
69
+
`EventSource`supporta le richieste cross-origin, come`fetch`e qualunque altro metodo di rete. Possiamo usare qualunque URL:
70
70
71
71
```js
72
72
let source =newEventSource("https://another-site.com/events");
73
73
```
74
+
Il server remoto otterrà l'header `Origin` e dovrà rispondere con `Access-Control-Allow-Origin` per continuare.
74
75
75
-
The remote server will get the `Origin` header and must respond with `Access-Control-Allow-Origin` to proceed.
76
-
77
-
To pass credentials, we should set the additional option `withCredentials`, like this:
76
+
Per inviare credenziali, dovremmo impostare le opzioni aggiuntive `withCredentials`, in questo modo:
78
77
79
78
```js
80
79
let source =newEventSource("https://another-site.com/events", {
81
80
withCredentials:true
82
81
});
83
82
```
84
83
85
-
Please see the chapter <info:fetch-crossorigin>for more details about cross-origin headers.
84
+
Si prega di guardare il capitolo <info:fetch-crossorigin>per maggiori informazioni sugli headers cross-origin.
86
85
87
86
88
-
## Reconnection
87
+
## Riconnessione
89
88
90
-
Upon creation, `new EventSource`connects to the server, and if the connection is broken -- reconnects.
89
+
In fase di creazione, `new EventSource`si connette al server, e se la connessione si interrompe -- si riconnette.
91
90
92
-
That's very convenient, as we don't have to care about it.
91
+
Ciòè molto conveniente, dal momento che non ci dobbiamo curare della cosa.
93
92
94
-
There's a small delay between reconnections, a few seconds by default.
93
+
C'è un piccolo ritardo tra le riconessioni, pochi secondi di default.
95
94
96
-
The server can set the recommended delay using`retry:`in response (in milliseconds):
95
+
Il server può impostare il ritardo raccomandato usando`retry:`nella risposta (in millisecondi)
97
96
98
97
```js
99
98
retry:15000
100
99
data: Hello, I set the reconnection delay to 15 seconds
101
100
```
102
101
103
-
The`retry:`may come both together with some data, or as a standalone message.
102
+
Il`retry:`può arrivare insieme ad altri dati, o come messaggio singolo.
104
103
105
-
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.
104
+
Il browser dovrebbe attendere questi millisecondi prima di riconettersi. O anche di più, ad esempio se il browser sa (dall'OS) che non c'è connessione in quel momento, può attendere fino a quando la connessione non ritorna, e successivamente riprovare.
106
105
107
-
-If the server wants the browser to stop reconnecting, it should respond with HTTP status 204.
108
-
-If the browser wants to close the connection, it should call`eventSource.close()`:
106
+
-Se il server vuole che il browser smetta di riconnettersi, dovrebbe rispondere con uno status HTTP 204.
107
+
-Se il browser vuole chiudere la connessione, dovrebbe chiamare il metodo`eventSource.close()`:
109
108
110
109
```js
111
110
let eventSource =newEventSource(...);
112
111
113
112
eventSource.close();
114
113
```
115
-
116
-
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.
114
+
Inoltre, non avverrà alcuna riconnessione se la risposta ha un `Content-type` non valido o se il suo HTTP status è diverso da 301, 307, 200 o 204. In questi casi verrà emesso l'evento `"error"`, e il browser non si riconnetterà.
117
115
118
116
```smart
119
-
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`.
117
+
Quando una connessione è finalemente chiusa, non ci sarà modo di "riaprirla". Se volessimo riconnetterci nuovamente, dovremmo ricreare un nuovo `EventSource`.
120
118
```
121
119
122
120
## Message id
123
121
124
-
When a connection breaks due to network problems, either side can't be sure which messages were received, and which weren't.
125
-
126
-
To correctly resume the connection, each message should have an `id` field, like this:
127
-
122
+
Quando una connessione si interrompe per motivi di problemi di rete, ogni lato non può essere sicuro di quale messaggi siano stati ricevuti, e quali no.
123
+
Per riprendere correttamente la connessione, ogni messaggio dovrebbe avere un campo `id`, come questo:
128
124
```
129
125
data: Message 1
130
126
id: 1
@@ -136,41 +132,40 @@ data: Message 3
136
132
data: of two lines
137
133
id: 3
138
134
```
135
+
Quando viene ricevuto un messaggio con `id:`, il browser:
139
136
140
-
When a message with `id:` is received, the browser:
141
-
142
-
- Sets the property `eventSource.lastEventId` to its value.
143
-
- Upon reconnection sends the header `Last-Event-ID` with that `id`, so that the server may re-send following messages.
137
+
- Imposta la proprietà`eventSource.lastEventId` su quel valore.
138
+
- In fase di riconnessione invia l'header `Last-Event-ID` con quell'`id`, in modo da permettere al server di reinviare i messaggi successivi.
144
139
145
140
```smart header="Put `id:` after `data:`"
146
-
Please note: the `id`is appended below message `data`by the server, to ensure that`lastEventId`is updated after the message is received.
141
+
Nota bene: l'`id`viene aggiunto sotto il messaggio `data`dal server, per assicurarsi che`lastEventId`venga aggiornato solamente dopo che il messaggio sia stato ricevuto.
147
142
```
148
143
149
-
## Connection status: readyState
144
+
## Stato della conessione: readyState
150
145
151
-
The `EventSource` object has `readyState` property, that has one of three values:
146
+
L'oggetto `EventSource` possiede la proprietà `readyState`, che assume uno tra questi tre valori:
152
147
153
148
```js no-beautify
154
-
EventSource.CONNECTING = 0; // connecting or reconnecting
155
-
EventSource.OPEN = 1; // connected
156
-
EventSource.CLOSED = 2; // connection closed
149
+
EventSource.CONNECTING = 0; // cnnessione o riconnessione
150
+
EventSource.OPEN = 1; // connesso
151
+
EventSource.CLOSED = 2; // connessione chiusa
157
152
```
158
153
159
-
When an object is created, or the connection is down, it's always`EventSource.CONNECTING` (equals`0`).
154
+
Quando viene creato un oggetto, o la connessione è assente, è sempre`EventSource.CONNECTING` (equivale a`0`).
160
155
161
-
We can query this property to know the state of`EventSource`.
156
+
Possiamo interrogare questa proprietà per sapere lo stato di`EventSource`.
162
157
163
-
## Event types
158
+
## Tipi di evento
164
159
165
-
By default `EventSource`object generates three events:
160
+
Di base l'oggetto `EventSource`genera tre eventi:
166
161
167
-
-`message` -- a message received, available as`event.data`.
168
-
-`open` -- the connection is open.
169
-
-`error` -- the connection could not be established, e.g. the server returned HTTP 500 status.
162
+
-`message` -- un messaggio ricevuto, disponibile come`event.data`.
163
+
-`open` -- la connessione è aperta.
164
+
-`error` -- la connessaione non può essere stabilita, ad esempio, il server ha risposto con lo status HTTP 500.
170
165
171
-
The server may specify another type of event with `event: ...`at the event start.
166
+
Il server può specificare un altro tipo di evento con `event: ...`all'inizio dell'evento.
172
167
173
-
For example:
168
+
Per esempio:
174
169
175
170
```
176
171
event: join
@@ -182,7 +177,7 @@ event: leave
182
177
data: Bob
183
178
```
184
179
185
-
To handle custom events, we must use `addEventListener`, not`onmessage`:
180
+
Per gestire eventi custom, dobbiamo usare `addEventListener`, e non`onmessage`:
Here's the server that sends messages with`1`, `2`, `3`, then `bye`and breaks the connection.
198
+
Qui c'è il server che invia messaggi con`1`, `2`, `3`, ed infine `bye`interrompendo la connessione.
204
199
205
-
Then the browser automatically reconnects.
200
+
Dopo il browser si riconnette automaticamente.
206
201
207
202
[codetabs src="eventsource"]
208
203
209
-
## Summary
204
+
## Riepilogo
210
205
211
-
`EventSource`object automatically establishes a persistent connection and allows the server to send messages over it.
206
+
L'oggetto `EventSource`stabilisce automaticamente una connessione persistente e permette al server di inviare dei messaggi attraverso di essa.
212
207
213
-
It offers:
214
-
-Automatic reconnect, with tunable `retry`timeout.
215
-
-Message ids to resume events, the last received identifier is sent in `Last-Event-ID`header upon reconnection.
216
-
-The current state is in the `readyState` property.
208
+
Offrendo:
209
+
-Riconnessione automatica, con timeout di `retry`regolabili.
210
+
-Id dei messaggi per riprendere gli eventi, l'ultimo id ricevuto viene inviato nell'header `Last-Event-ID`in fase di riconnessione.
211
+
-Lo stato corrente è dentro la proprietà`readyState`.
217
212
218
-
That makes`EventSource`a viable alternative to`WebSocket`, as it's more low-level and lacks such built-in features (though they can be implemented).
213
+
Ciò rende`EventSource`una valida alternativa ai`WebSocket`, il quale è più a basso livello e manca di alcune funzionalitàbuilt-in (sebbene possasno essere implementate).
219
214
220
-
In many real-life applications, the power of`EventSource`is just enough.
215
+
In molte applicazioni reali, la potenza di`EventSource`è già sufficiente.
221
216
222
-
Supported in all modern browsers (not IE).
217
+
Supportato in tutti i browser moderni (non IE).
223
218
224
-
The syntax is:
219
+
La sintassi è:
225
220
226
221
```js
227
222
let source =newEventSource(url, [credentials]);
228
223
```
229
224
230
-
The second argument has only one possible option: `{ withCredentials: true }`, it allows sending cross-origin credentials.
225
+
Il secondo argomento ha solo una opzione possibile: `{ withCredentials: true }`, il quale permette di inviare credenziali cross-origin.
231
226
232
-
Overall cross-origin security is same as for `fetch`and other network methods.
227
+
Complessivamente la sicurezza del cross-origin è la stessa di `fetch`e altri metodi di rete.
233
228
234
-
### Properties of an `EventSource` object
229
+
### Proprietà di un oggetto `EventSource`
235
230
236
231
`readyState`
237
-
: The current connection state: either `EventSource.CONNECTING (=0)`, `EventSource.OPEN (=1)`or`EventSource.CLOSED (=2)`.
232
+
: Lo stato corrente della connessione: uno tra `EventSource.CONNECTING (=0)`, `EventSource.OPEN (=1)`o`EventSource.CLOSED (=2)`.
238
233
239
234
`lastEventId`
240
-
: The last received `id`. Upon reconnection the browser sends it in the header `Last-Event-ID`.
235
+
: L'ultimo `id` ricevuto.In fase di riconnessione il browser lo invia nell'header `Last-Event-ID`.
241
236
242
-
### Methods
237
+
### Metodi
243
238
244
239
`close()`
245
-
: Closes the connection.
240
+
: Chiude la connessione.
246
241
247
-
### Events
242
+
### Eventi
248
243
249
244
`message`
250
-
: Message received, the data is in`event.data`.
245
+
: Messagio ricevuto, il dato è dentro`event.data`.
251
246
252
247
`open`
253
-
: The connection is established.
248
+
: La connessione è stabilita.
254
249
255
250
`error`
256
-
: In case of an error, including both lost connection (will auto-reconnect) and fatal errors. We can check `readyState`to see if the reconnection is being attempted.
251
+
: In caseo di error, inclusi sia la connessione persa (si riconnetterà automaticamente), e errori fatali. Possiamo controllare `readyState`per vedere se è stata tentata la riconnessione.
257
252
258
-
The server may set a custom event name in `event:`. Such events should be handled using `addEventListener`, not`on<event>`.
253
+
Il server può impostare un evento custom dentro `event:`. Questi eventi andrebbero gestiti usando `addEventListener`, e non`on<event>`.
259
254
260
-
### Server response format
255
+
### Formato della risposta del server
261
256
262
-
The server sends messages, delimited by`\n\n`.
257
+
Il server invia messaggi, delimitati da`\n\n`.
263
258
264
-
A message may have following fields:
259
+
Un messaggio può avere i seguenti campi:
265
260
266
-
-`data:` -- message body, a sequence of multiple `data`is interpreted as a single message, with`\n`between the parts.
267
-
-`id:` -- renews `lastEventId`, sent in`Last-Event-ID`on reconnect.
268
-
-`retry:` -- recommends a retry delay for reconnections in ms. There's no way to set it from JavaScript.
261
+
-`data:` -- corpo del messaggio, una sequenza di `data`multipli viene intrpretata come un messaggio singolo, con`\n`tra la parti.
262
+
-`id:` -- aggiorna il `lastEventId`, inviato dentro`Last-Event-ID`in fase di riconnnessione.
263
+
-`retry:` -- raccomnda una ritardo nel tentativo di riconessione in millisecondi. Non c'è modo di impostarlo da JavaScript.
269
264
-`event:` -- event name, must precede `data:`.
270
265
271
-
A message may include one or more fields in any order, but `id:`usually goes the last.
266
+
Un messaggio può includere uno o più campi in qualunque ordine, ma l'`id:`solitamente va per ultimo.
0 commit comments