Skip to content

Commit 7de52cc

Browse files
authored
Merge pull request #381 from homero304/Server-Sent-Events
Server Sent Events
2 parents 304689c + aff46c4 commit 7de52cc

File tree

2 files changed

+122
-122
lines changed

2 files changed

+122
-122
lines changed
Lines changed: 111 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1,271 +1,271 @@
1-
# Server Sent Events
1+
# Eventos enviados por el servidor
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 especificación de los [Eventos enviados por el servidor](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) describe una clase incorporada `EventSource`, que mantiene la conexión con el servidor y permite recibir eventos de él.
44

5-
Similar to `WebSocket`, the connection is persistent.
5+
Similar a `WebSocket`, la conexión es persistente.
66

7-
But there are several important differences:
7+
Pero existen varias diferencias importantes:
88

99
| `WebSocket` | `EventSource` |
1010
|-------------|---------------|
11-
| Bi-directional: both client and server can exchange messages | One-directional: only server sends data |
12-
| Binary and text data | Only text |
13-
| WebSocket protocol | Regular HTTP |
11+
| Bidireccional: tanto el cliente como el servidor pueden intercambiar mensajes | Unidireccional: solo el servidor envía datos |
12+
| Datos binarios y de texto | Solo texto |
13+
| Protocolo WebSocket | HTTP regular |
1414

15-
`EventSource` is a less-powerful way of communicating with the server than `WebSocket`.
15+
`EventSource` es una forma menos poderosa de comunicarse con el servidor que `WebSocket`.
1616

17-
Why should one ever use it?
17+
¿Por qué debería uno usarlo?
1818

19-
The main reason: it's simpler. In many applications, the power of `WebSocket` is a little bit too much.
19+
El motivo principal: es más sencillo. En muchas aplicaciones, el poder de `WebSocket` es demasiado.
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+
Necesitamos recibir un flujo de datos del servidor: tal vez mensajes de chat o precios de mercado, o lo que sea. Para eso es bueno `EventSource`. También admite la reconexión automática, algo que debemos implementar manualmente con `WebSocket`. Además, es HTTP común, no un protocolo nuevo.
2222

23-
## Getting messages
23+
## Recibir mensajes
2424

25-
To start receiving messages, we just need to create `new EventSource(url)`.
25+
Para comenzar a recibir mensajes, solo necesitamos crear un `new EventSource(url)`.
2626

27-
The browser will connect to `url` and keep the connection open, waiting for events.
27+
El navegador se conectará a la `url` y mantendrá la conexión abierta, esperando eventos.
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+
El servidor debe responder con el estado 200 y el encabezado `Content-Type:text/event-stream`, entonces mantener la conexión y escribir mensajes en el formato especial, así:
3030

3131
```
32-
data: Message 1
32+
data: Mensaje 1
3333
34-
data: Message 2
34+
data: Mensaje 2
3535
36-
data: Message 3
37-
data: of two lines
36+
data: Mensaje 3
37+
data: de dos líneas
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 mensaje de texto va después de `data:`, el espacio después de los dos puntos es opcional.
41+
- Los mensajes están delimitados con saltos de línea dobles `\n\n`.
42+
- Para enviar un salto de línea `\n`, podemos enviar inmediatamente un `data:` (tercer mensaje arriba) más.
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+
En la práctica, los mensajes complejos generalmente se envían codificados en JSON. Los saltos de línea están codificados así `\n` dentro de los mensajes, por lo que los mensajes `data:` multilínea no son necesarios.
4545

46-
For instance:
46+
Por ejemplo:
4747

4848
```js
49-
data: {"user":"John","message":"First line*!*\n*/!* Second line"}
49+
data: {"user":"John","message":"Primera línea*!*\n*/!* Segunda línea"}
5050
```
5151

52-
...So we can assume that one `data:` holds exactly one message.
52+
... Entonces podemos asumir que un `data:` contiene exactamente un mensaje.
5353

54-
For each such message, the `message` event is generated:
54+
Para cada uno de estos mensajes, se genera el evento `message`:
5555

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

5959
eventSource.onmessage = function(event) {
60-
console.log("New message", event.data);
61-
// will log 3 times for the data stream above
60+
console.log("Nuevo mensaje", event.data);
61+
// registrará apuntes 3 veces para el flujo de datos anterior
6262
};
6363

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

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

69-
`EventSource` supports cross-origin requests, like `fetch` any other networking methods. We can use any URL:
69+
`EventSource` admite solicitudes cross-origin, como `fetch` o cualquier otro método de red. Podemos utilizar cualquier URL:
7070

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

75-
The remote server will get the `Origin` header and must respond with `Access-Control-Allow-Origin` to proceed.
75+
El servidor remoto obtendrá el encabezado `Origin` y debe responder con `Access-Control-Allow-Origin` para continuar.
7676

77-
To pass credentials, we should set the additional option `withCredentials`, like this:
77+
Para pasar las credenciales, debemos configurar la opción adicional `withCredentials`, así:
7878

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

85-
Please see the chapter <info:fetch-crossorigin> for more details about cross-origin headers.
85+
Consulte el capítulo <info:fetch-crossorigin> para obtener más detalles sobre los encabezados cross-origin.
8686

8787

88-
## Reconnection
88+
## Reconexión
8989

90-
Upon creation, `new EventSource` connects to the server, and if the connection is broken -- reconnects.
90+
Tras la creación con `new EventSource`, el cliente se conecta al servidor y, si la conexión se interrumpe, se vuelve a conectar.
9191

92-
That's very convenient, as we don't have to care about it.
92+
Eso es muy conveniente, ya que no tenemos que preocuparnos por eso.
9393

94-
There's a small delay between reconnections, a few seconds by default.
94+
Hay un pequeño retraso entre las reconexiones, unos segundos por defecto.
9595

96-
The server can set the recommended delay using `retry:` in response (in milliseconds):
96+
El servidor puede establecer la demora recomendada usando `retry:` dentro de la respuesta (en milisegundos):
9797

9898
```js
9999
retry: 15000
100-
data: Hello, I set the reconnection delay to 15 seconds
100+
data: Hola, configuré el retraso de reconexión en 15 segundos
101101
```
102102

103-
The `retry:` may come both together with some data, or as a standalone message.
103+
El `retry:` puede venir junto con algunos datos, o como un mensaje independiente.
104104

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.
105+
El navegador debe esperar esa cantidad de milisegundos antes de volver a conectarse. O más, por ejemplo: si el navegador sabe (desde el sistema operativo) que no hay conexión de red en este momento, puede esperar hasta que aparezca la conexión y luego volver a intentarlo.
106106

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()`:
107+
- Si el servidor desea que el navegador deje de volver a conectarse, debería responder con el estado HTTP 204.
108+
- Si el navegador quiere cerrar la conexión, debe llamar a `eventSource.close()`:
109109

110110
```js
111111
let eventSource = new EventSource(...);
112112

113113
eventSource.close();
114114
```
115115

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.
116+
Además, no habrá reconexión si la respuesta tiene un `Content-Type` incorrecto o su estado HTTP difiere de 301, 307, 200 y 204. En tales casos, se emitirá el evento `"error"` y el navegador no se volverá a conectar.
117117

118118
```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`.
119+
Cuando una conexión finalmente se cierra, no hay forma de "reabrirla". Si queremos conectarnos de nuevo, simplemente crea un nuevo `EventSource`.
120120
```
121121

122-
## Message id
122+
## ID del mensaje
123123

124-
When a connection breaks due to network problems, either side can't be sure which messages were received, and which weren't.
124+
Cuando una conexión se interrumpe debido a problemas de red, ninguna de las partes puede estar segura de qué mensajes se recibieron y cuáles no.
125125

126-
To correctly resume the connection, each message should have an `id` field, like this:
126+
Para reanudar correctamente la conexión, cada mensaje debe tener un campo `id`, así:
127127

128128
```
129-
data: Message 1
129+
data: Mensaje 1
130130
id: 1
131131
132-
data: Message 2
132+
data: Mensaje 2
133133
id: 2
134134
135-
data: Message 3
136-
data: of two lines
135+
data: Mensaje 3
136+
data: de dos líneas
137137
id: 3
138138
```
139139

140-
When a message with `id:` is received, the browser:
140+
Cuando se recibe un mensaje con `id:`, el navegador:
141141

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.
142+
- Establece la propiedad `eventSource.lastEventId` a su valor.
143+
- Tras la reconexión, el navegador envía el encabezado `Last-Event-ID` con ese `id`, para que el servidor pueda volver a enviar los siguientes mensajes.
144144

145-
```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.
145+
```smart header="Pon `id:` después de `data:`"
146+
Ten en cuenta: el `id` es adjuntado debajo del mensaje `data` por el servidor, para garantizar que `lastEventId` se actualice después de recibir el mensaje.
147147
```
148148
149-
## Connection status: readyState
149+
## Estado de conexión: readyState
150150
151-
The `EventSource` object has `readyState` property, that has one of three values:
151+
El objeto `EventSource` tiene la propiedad `readyState`, que tiene uno de tres valores:
152152
153153
```js no-beautify
154-
EventSource.CONNECTING = 0; // connecting or reconnecting
155-
EventSource.OPEN = 1; // connected
156-
EventSource.CLOSED = 2; // connection closed
154+
EventSource.CONNECTING = 0; // conectando o reconectando
155+
EventSource.OPEN = 1; // conectado
156+
EventSource.CLOSED = 2; // conexión cerrada
157157
```
158158

159-
When an object is created, or the connection is down, it's always `EventSource.CONNECTING` (equals `0`).
159+
Cuando se crea un objeto, o la conexión no funciona, siempre es `EventSource.CONNECTING` (es igual a `0`).
160160

161-
We can query this property to know the state of `EventSource`.
161+
Podemos consultar esta propiedad para conocer el estado de `EventSource`.
162162

163-
## Event types
163+
## Tipos de eventos
164164

165-
By default `EventSource` object generates three events:
165+
Por defecto, el objeto `EventSource` genera tres eventos:
166166

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.
167+
- `message` -- un mensaje recibido, disponible como `event.data`.
168+
- `open` -- la conexión está abierta.
169+
- `error` -- no se pudo establecer la conexión, por ejemplo, el servidor devolvió el estado HTTP 500.
170170

171-
The server may specify another type of event with `event: ...` at the event start.
171+
El servidor puede especificar otro tipo de evento con `event: ...` al inicio del evento.
172172

173-
For example:
173+
Por ejemplo:
174174

175175
```
176176
event: join
177177
data: Bob
178178
179-
data: Hello
179+
data: Hola
180180
181181
event: leave
182182
data: Bob
183183
```
184184

185-
To handle custom events, we must use `addEventListener`, not `onmessage`:
185+
Para manejar eventos personalizados, debemos usar `addEventListener`, no `onmessage`:
186186

187187
```js
188188
eventSource.addEventListener('join', event => {
189-
alert(`Joined ${event.data}`);
189+
alert(`Se unió ${event.data}`);
190190
});
191191

192192
eventSource.addEventListener('message', event => {
193-
alert(`Said: ${event.data}`);
193+
alert(`Dijo: ${event.data}`);
194194
});
195195

196196
eventSource.addEventListener('leave', event => {
197-
alert(`Left ${event.data}`);
197+
alert(`Salió ${event.data}`);
198198
});
199199
```
200200

201-
## Full example
201+
## Ejemplo completo
202202

203-
Here's the server that sends messages with `1`, `2`, `3`, then `bye` and breaks the connection.
203+
Aquí está el servidor que envía mensajes con `1`, `2`, `3`, luego `bye` y cierra la conexión.
204204

205-
Then the browser automatically reconnects.
205+
Luego, el navegador se vuelve a conectar automáticamente.
206206

207207
[codetabs src="eventsource"]
208208

209-
## Summary
209+
## Resumen
210210

211-
`EventSource` object automatically establishes a persistent connection and allows the server to send messages over it.
211+
El objeto `EventSource` establece automáticamente una conexión persistente y permite al servidor enviar mensajes a través de él.
212212

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.
213+
Ofrece:
214+
- Reconexión automática, con tiempo de espera de `reintento` ajustable.
215+
- IDs en cada mensaje para reanudar los eventos, el último identificador recibido se envía en el encabezado `Last-Event-ID` al volver a conectarse.
216+
- El estado actual está en la propiedad `readyState`.
217217

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).
218+
Eso hace que `EventSource` sea una alternativa viable a `WebSocket`, ya que es de un nivel más bajo y carece de esas características integradas (aunque se pueden implementar).
219219

220-
In many real-life applications, the power of `EventSource` is just enough.
220+
En muchas aplicaciones de la vida real, el poder de `EventSource` es suficiente.
221221

222-
Supported in all modern browsers (not IE).
222+
Compatible con todos los navegadores modernos (no IE).
223223

224-
The syntax is:
224+
La sintaxis es:
225225

226226
```js
227227
let source = new EventSource(url, [credentials]);
228228
```
229229

230-
The second argument has only one possible option: `{ withCredentials: true }`, it allows sending cross-origin credentials.
230+
El segundo argumento tiene solo una opción posible: `{withCredentials: true}`, permite enviar credenciales de cross-origin.
231231

232-
Overall cross-origin security is same as for `fetch` and other network methods.
232+
La seguridad general de cross-origin es la misma que para `fetch` y otros métodos de red.
233233

234-
### Properties of an `EventSource` object
234+
### Propiedades de un objeto `EventSource`
235235

236236
`readyState`
237-
: The current connection state: either `EventSource.CONNECTING (=0)`, `EventSource.OPEN (=1)` or `EventSource.CLOSED (=2)`.
237+
: El estado de conexión actual: `EventSource.CONNECTING (=0)`, `EventSource.OPEN (=1)` o `EventSource.CLOSED (=2)`.
238238

239239
`lastEventId`
240-
: The last received `id`. Upon reconnection the browser sends it in the header `Last-Event-ID`.
240+
: El último `id` recibido. Tras la reconexión, el navegador lo envía en el encabezado `Last-Event-ID`.
241241

242-
### Methods
242+
### Métodos
243243

244244
`close()`
245-
: Closes the connection.
245+
: Cierra la conexión.
246246

247-
### Events
247+
### Eventos
248248

249249
`message`
250-
: Message received, the data is in `event.data`.
250+
: Mensaje recibido, los datos están en `event.data`.
251251

252252
`open`
253-
: The connection is established.
253+
: Se establece la conexión.
254254

255255
`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.
256+
: En caso de error, se incluyen tanto la pérdida de conexión (se reconectará automáticamente) como los errores fatales. Podemos comprobar `readyState` para ver si se está intentando la reconexión.
257257

258-
The server may set a custom event name in `event:`. Such events should be handled using `addEventListener`, not `on<event>`.
258+
El servidor puede establecer un nombre de evento personalizado en `event:`. Tales eventos deben manejarse usando `addEventListener`, no `on<evento>`.
259259

260-
### Server response format
260+
### Formato de respuesta del servidor
261261

262-
The server sends messages, delimited by `\n\n`.
262+
El servidor envía mensajes, delimitados por `\n\n`.
263263

264-
A message may have following fields:
264+
Un mensaje puede tener los siguientes campos:
265265

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.
269-
- `event:` -- event name, must precede `data:`.
266+
- `data:` -- cuerpo del mensaje, una secuencia de múltiples `datos` se interpreta como un solo mensaje, con `\n` entre las partes.
267+
- `id:` -- renueva `lastEventId`, enviado en el encabezado `Last-Event-ID` al volver a conectarse.
268+
- `retry:` -- recomienda una demora de reintento para las reconexiones en milisegundos. No hay forma de configurarlo desde JavaScript.
269+
- `event:` -- nombre del evento, debe preceder a `data:`.
270270

271-
A message may include one or more fields in any order, but `id:` usually goes the last.
271+
Un mensaje puede incluir uno o más campos en cualquier orden, pero `id:` suele ser el último.

0 commit comments

Comments
 (0)