Skip to content

Commit 26e8ab1

Browse files
Prima stesura completa articolo
1 parent 4def447 commit 26e8ab1

File tree

1 file changed

+89
-94
lines changed

1 file changed

+89
-94
lines changed
Lines changed: 89 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,32 @@
11
# Server Sent Events
22

3-
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.
44

5-
Similar to `WebSocket`, the connection is persistent.
5+
In modo simile ai `WebSocket`, la connessione è persistente.
66

7-
But there are several important differences:
7+
Ci sono però delle differenze sostanziali:
88

99
| `WebSocket` | `EventSource` |
1010
|-------------|---------------|
1111
| Bi-directional: both client and server can exchange messages | One-directional: only server sends data |
1212
| Binary and text data | Only text |
1313
| WebSocket protocol | Regular HTTP |
1414

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`.
1616

17-
Why should one ever use it?
17+
Perchè dovremmo usarli?
1818

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.
2020

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.
2222

23-
## Getting messages
23+
## Ottenere i messaggi
2424

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)`.
2626

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.
2828

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:
3030

3131
```
3232
data: Message 1
@@ -37,94 +37,90 @@ data: Message 3
3737
data: of two lines
3838
```
3939

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).
4343

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
4545

46-
For instance:
46+
Ad esempio:
4747

4848
```js
4949
data: {"user":"John","message":"First line*!*\n*/!* Second line"}
5050
```
5151

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.
5353

54-
For each such message, the `message` event is generated:
54+
Per ognuno di questi messaggi, viene generato l'evento `message`:
5555

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

5959
eventSource.onmessage = function(event) {
6060
console.log("New message", event.data);
61-
// will log 3 times for the data stream above
61+
//logghera' 3 volte per il data stream poco sopra
6262
};
6363

64-
// or eventSource.addEventListener('message', ...)
64+
// oppure eventSource.addEventListener('message', ...)
6565
```
6666

67-
### Cross-origin requests
67+
### Richieste Cross-origin
6868

69-
`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:
7070

7171
```js
7272
let source = new EventSource("https://another-site.com/events");
7373
```
74+
Il server remoto otterrà l'header `Origin` e dovrà rispondere con `Access-Control-Allow-Origin` per continuare.
7475

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:
7877

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

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.
8685

8786

88-
## Reconnection
87+
## Riconnessione
8988

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.
9190

92-
That's very convenient, as we don't have to care about it.
91+
Ci&ograve; &egrave; molto conveniente, dal momento che non ci dobbiamo curare della cosa.
9392

94-
There's a small delay between reconnections, a few seconds by default.
93+
C'&egrave; un piccolo ritardo tra le riconessioni, pochi secondi di default.
9594

96-
The server can set the recommended delay using `retry:` in response (in milliseconds):
95+
Il server pu&ograve; impostare il ritardo raccomandato usando `retry:` nella risposta (in millisecondi)
9796

9897
```js
9998
retry: 15000
10099
data: Hello, I set the reconnection delay to 15 seconds
101100
```
102101

103-
The `retry:` may come both together with some data, or as a standalone message.
102+
Il `retry:` pu&ograve; arrivare insieme ad altri dati, o come messaggio singolo.
104103

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&ugrave;, ad esempio se il browser sa (dall'OS) che non c'&egrave; connessione in quel momento, pu&ograve; attendere fino a quando la connessione non ritorna, e successivamente riprovare.
106105

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()`:
109108

110109
```js
111110
let eventSource = new EventSource(...);
112111

113112
eventSource.close();
114113
```
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&agrave; alcuna riconnessione se la risposta ha un `Content-type` non valido o se il suo HTTP status &egrave; diverso da 301, 307, 200 o 204. In questi casi verr&agrave; emesso l'evento `"error"`, e il browser non si riconnetter&agrave;.
117115

118116
```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 &egrave; finalemente chiusa, non ci sar&agrave; modo di "riaprirla". Se volessimo riconnetterci nuovamente, dovremmo ricreare un nuovo `EventSource`.
120118
```
121119

122120
## Message id
123121

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&ograve; 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:
128124
```
129125
data: Message 1
130126
id: 1
@@ -136,41 +132,40 @@ data: Message 3
136132
data: of two lines
137133
id: 3
138134
```
135+
Quando viene ricevuto un messaggio con `id:`, il browser:
139136

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&agrave; `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.
144139

145140
```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.
147142
```
148143
149-
## Connection status: readyState
144+
## Stato della conessione: readyState
150145
151-
The `EventSource` object has `readyState` property, that has one of three values:
146+
L'oggetto `EventSource` possiede la propriet&agrave; `readyState`, che assume uno tra questi tre valori:
152147
153148
```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
157152
```
158153

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 &egrave; assente, &egrave; sempre `EventSource.CONNECTING` (equivale a `0`).
160155

161-
We can query this property to know the state of `EventSource`.
156+
Possiamo interrogare questa propriet&agrave; per sapere lo stato di `EventSource`.
162157

163-
## Event types
158+
## Tipi di evento
164159

165-
By default `EventSource` object generates three events:
160+
Di base l'oggetto `EventSource` genera tre eventi:
166161

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 &egrave; aperta.
164+
- `error` -- la connessaione non pu&ograve; essere stabilita, ad esempio, il server ha risposto con lo status HTTP 500.
170165

171-
The server may specify another type of event with `event: ...` at the event start.
166+
Il server pu&ograve; specificare un altro tipo di evento con `event: ...` all'inizio dell'evento.
172167

173-
For example:
168+
Per esempio:
174169

175170
```
176171
event: join
@@ -182,7 +177,7 @@ event: leave
182177
data: Bob
183178
```
184179

185-
To handle custom events, we must use `addEventListener`, not `onmessage`:
180+
Per gestire eventi custom, dobbiamo usare `addEventListener`, e non `onmessage`:
186181

187182
```js
188183
eventSource.addEventListener('join', event => {
@@ -198,74 +193,74 @@ eventSource.addEventListener('leave', event => {
198193
});
199194
```
200195

201-
## Full example
196+
## Esempio completo
202197

203-
Here's the server that sends messages with `1`, `2`, `3`, then `bye` and breaks the connection.
198+
Qui c'&egrave; il server che invia messaggi con `1`, `2`, `3`, ed infine `bye` interrompendo la connessione.
204199

205-
Then the browser automatically reconnects.
200+
Dopo il browser si riconnette automaticamente.
206201

207202
[codetabs src="eventsource"]
208203

209-
## Summary
204+
## Riepilogo
210205

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.
212207

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 &egrave; dentro la propriet&agrave; `readyState`.
217212

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&ograve; rende `EventSource` una valida alternativa ai `WebSocket`, il quale &egrave; pi&ugrave; a basso livello e manca di alcune funzionalit&agrave; built-in (sebbene possasno essere implementate).
219214

220-
In many real-life applications, the power of `EventSource` is just enough.
215+
In molte applicazioni reali, la potenza di `EventSource` &egrave; gi&agrave; sufficiente.
221216

222-
Supported in all modern browsers (not IE).
217+
Supportato in tutti i browser moderni (non IE).
223218

224-
The syntax is:
219+
La sintassi &egrave;:
225220

226221
```js
227222
let source = new EventSource(url, [credentials]);
228223
```
229224

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.
231226

232-
Overall cross-origin security is same as for `fetch` and other network methods.
227+
Complessivamente la sicurezza del cross-origin &egrave; la stessa di `fetch` e altri metodi di rete.
233228

234-
### Properties of an `EventSource` object
229+
### Propriet&agrave; di un oggetto `EventSource`
235230

236231
`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)`.
238233

239234
`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`.
241236

242-
### Methods
237+
### Metodi
243238

244239
`close()`
245-
: Closes the connection.
240+
: Chiude la connessione.
246241

247-
### Events
242+
### Eventi
248243

249244
`message`
250-
: Message received, the data is in `event.data`.
245+
: Messagio ricevuto, il dato &egrave; dentro `event.data`.
251246

252247
`open`
253-
: The connection is established.
248+
: La connessione &egrave; stabilita.
254249

255250
`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&agrave; automaticamente), e errori fatali. Possiamo controllare `readyState` per vedere se &egrave; stata tentata la riconnessione.
257252

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&ograve; impostare un evento custom dentro `event:`. Questi eventi andrebbero gestiti usando `addEventListener`, e non `on<event>`.
259254

260-
### Server response format
255+
### Formato della risposta del server
261256

262-
The server sends messages, delimited by `\n\n`.
257+
Il server invia messaggi, delimitati da `\n\n`.
263258

264-
A message may have following fields:
259+
Un messaggio pu&ograve; avere i seguenti campi:
265260

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'&egrave; modo di impostarlo da JavaScript.
269264
- `event:` -- event name, must precede `data:`.
270265

271-
A message may include one or more fields in any order, but `id:` usually goes the last.
266+
Un messaggio pu&ograve; includere uno o pi&ugrave; campi in qualunque ordine, ma l'`id:` solitamente va per ultimo.

0 commit comments

Comments
 (0)