Skip to content

Commit 39ecdf6

Browse files
Part 3. 5.12 Server Sent Events 번역
1 parent 4b921fd commit 39ecdf6

1 file changed

Lines changed: 113 additions & 113 deletions

File tree

Lines changed: 113 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -1,271 +1,271 @@
1-
# Server Sent Events
1+
# 서버 전송 이벤트
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+
[서버 전송 이벤트(Server-Sent Events)](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) 명세는 내장 클래스 `EventSource`를 정의합니다. `EventSource`를 사용하면 서버와 커넥션을 유지하면서 서버가 보내는 이벤트를 받을 수 있습니다.
44

5-
Similar to `WebSocket`, the connection is persistent.
5+
`WebSocket`과 마찬가지로 서버 전송 이벤트에서도 커넥션은 지속됩니다.
66

7-
But there are several important differences:
7+
그런데 둘 사이엔 중요한 차이가 몇 가지 있습니다.
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+
| 양방향 통신. 클라이언트와 서버 모두 메시지를 주고받을 수 있음 | 단방향 통신. 서버만 데이터를 보냄 |
12+
| 바이너리와 텍스트 데이터 전송 가능 | 텍스트만 전송 가능 |
13+
| 웹소켓 프로토콜 사용 | 일반 HTTP 사용 |
1414

15-
`EventSource` is a less-powerful way of communicating with the server than `WebSocket`.
15+
이렇게 보면 `EventSource``WebSocket`보다 서버와 통신하는 능력이 부족한 수단 같아 보입니다.
1616

17-
Why should one ever use it?
17+
그런데도 `EventSource`를 써야 할 이유가 있을까요?
1818

19-
The main reason: it's simpler. In many applications, the power of `WebSocket` is a little bit too much.
19+
물론 있습니다. 단순하다는 점이죠. 상당수 애플리케이션엔 `WebSocket`에서 제공하는 능력까지는 필요하지 않습니다.
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+
채팅 메시지나 주식 시세처럼 서버에서 흘러오는 데이터 스트림을 받기만 하면 되는 상황이라면 `EventSource`가 제격입니다. `EventSource``WebSocket`에선 직접 구현해야 하는 자동 재연결도 지원합니다. 게다가 새로운 프로토콜이 아니라 익숙한 HTTP를 그대로 사용합니다.
2222

23-
## Getting messages
23+
## 메시지 받기
2424

25-
To start receiving messages, we just need to create `new EventSource(url)`.
25+
서버에서 보내는 메시지는 브라우저에서 실행 중인 클라이언트 측 자바스크립트에서 `new EventSource(url)`를 만들기만 하면 받을 수 있습니다.
2626

27-
The browser will connect to `url` and keep the connection open, waiting for events.
27+
그러면 브라우저가 알아서 `url`로 접속해 커넥션을 열어둔 채 이벤트를 기다립니다.
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+
서버는 본문 전체를 보내는 대신 우선 상태 코드 200과 헤더 `Content-Type: text/event-stream`만 보내 응답한 뒤, 커넥션을 유지하면서 다음과 같은 특별한 형식의 메시지를 클라이언트로 흘려보냅니다.
3030

3131
```
32-
data: Message 1
32+
data: 메시지 1
3333
34-
data: Message 2
34+
data: 메시지 2
3535
36-
data: Message 3
37-
data: of two lines
36+
data: 메시지 3
37+
data: 두 번째 줄
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+
- 메시지 본문은 `data:` 뒤에 붙이는데, 콜론 뒤 공백은 생략할 수 있습니다.
41+
- 메시지끼리는 두 번의 줄바꿈 `\n\n`으로 구분합니다.
42+
- 줄바꿈 `\n`을 보내고 싶으면 바로 다음 줄에 `data:`를 한 번 더 씁니다(위 예시의 세 번째 메시지).
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+
실무에선 복잡한 메시지는 보통 JSON으로 인코딩해 보냅니다. JSON으로 인코딩하면 줄바꿈이 문자열 안에서 `\n`으로 처리되기 때문에 `data:`를 여러 줄로 나눠 쓸 일도 없습니다.
4545

46-
For instance:
46+
예시를 살펴봅시다.
4747

4848
```js
49-
data: {"user":"John","message":"First line*!*\n*/!* Second line"}
49+
data: {"user":"보라","message":"첫 번째 줄*!*\n*/!* 두 번째 줄"}
5050
```
5151

52-
...So we can assume that one `data:` holds exactly one message.
52+
이런 관례 덕분에 `data:` 하나가 곧 메시지 하나라고 생각해도 됩니다.
5353

54-
For each such message, the `message` event is generated:
54+
이렇게 메시지가 하나 도착할 때마다 `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("새 메시지", event.data);
61+
// 위 데이터 스트림이라면 세 번 출력됩니다.
6262
};
6363

64-
// or eventSource.addEventListener('message', ...)
64+
// eventSource.addEventListener('message', ...)를 사용해도 됩니다.
6565
```
6666

67-
### Cross-origin requests
67+
### 크로스 오리진 요청
6868

69-
`EventSource` supports cross-origin requests, like `fetch` any other networking methods. We can use any URL:
69+
`EventSource``fetch`를 비롯한 여타 네트워크 메서드처럼 크로스 오리진 요청을 지원합니다. 어떤 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+
`EventSource`로 접속한 크로스 오리진 원격 서버는 브라우저가 요청을 보낼 때 자동으로 붙인 `Origin` 헤더를 받습니다. 요청을 받은 서버는 응답에 `Access-Control-Allow-Origin` 헤더를 넣어 해당 오리진의 접근을 허용한다고 응답합니다.
7676

77-
To pass credentials, we should set the additional option `withCredentials`, like this:
77+
자격 증명을 함께 보내려면 다음과 같이 옵션 `withCredentials`를 추가로 설정합니다.
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+
크로스 오리진 헤더에 대한 자세한 내용은 <info:fetch-crossorigin> 챕터를 참고하세요.
8686

8787

88-
## Reconnection
88+
## 재연결
8989

90-
Upon creation, `new EventSource` connects to the server, and if the connection is broken -- reconnects.
90+
`new EventSource`로 객체를 만들면 브라우저가 알아서 서버에 커넥션을 엽니다. 이때 커넥션이 끊어져도 브라우저가 알아서 다시 접속합니다.
9191

92-
That's very convenient, as we don't have to care about it.
92+
재연결을 직접 신경 쓰지 않아도 되니 아주 편리하죠.
9393

94-
There's a small delay between reconnections, a few seconds by default.
94+
다만, 재연결 사이엔 짧은 지연이 있는데 기본값(브라우저에서 지정)은 몇 초 정도입니다.
9595

96-
The server can set the recommended delay using `retry:` in response (in milliseconds):
96+
재연결 지연 시간은 서버가 원하는 값으로 바꿀 수 있습니다. 서버는 응답에 `retry:`를 실어 권장 지연 시간을 밀리초 단위로 설정할 수 있습니다.
9797

9898
```js
9999
retry: 15000
100-
data: Hello, I set the reconnection delay to 15 seconds
100+
data: 안녕하세요. 재연결 지연 시간을 15초로 설정했습니다.
101101
```
102102

103-
The `retry:` may come both together with some data, or as a standalone message.
103+
`retry:`는 데이터와 함께 보낼 수도 있고 단독 메시지로 보낼 수도 있습니다.
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+
브라우저는 재연결하기 전에 지정된 시간만큼 기다립니다. 더 오래 기다리기도 합니다. 운영체제로부터 현재 네트워크 연결이 없다는 정보를 받았다면 연결이 살아날 때까지 기다렸다가 다시 시도합니다.
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+
- 서버 쪽에서 브라우저의 재연결 시도를 멈추고 싶다면 HTTP 상태 코드 204로 응답해야 합니다.
108+
- 브라우저 쪽에서 커넥션을 닫고 싶다면 `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+
이렇게 서버나 브라우저에서 명시적으로 재연결을 멈출 때 말고, 응답의 `Content-Type`이 올바르지 않거나 HTTP 상태 코드가 301, 307, 200, 204가 아닐 때도 재연결은 일어나지 않습니다. 이때는 `"error"` 이벤트가 발생하고 브라우저는 재연결을 시도하지 않습니다.
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+
한번 완전히 닫힌 커넥션은 '다시 열' 방법이 없습니다. 다시 접속하고 싶다면 새로운 `EventSource`를 만드세요.
120120
```
121121

122-
## Message id
122+
## 메시지 id
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+
네트워크 문제로 커넥션이 끊어지면 어떤 메시지가 도착했고 어떤 메시지가 유실됐는지 어느 쪽도 확신할 수 없습니다.
125125

126-
To correctly resume the connection, each message should have an `id` field, like this:
126+
커넥션을 정확히 이어가려면 다음과 같이 메시지마다 `id` 필드가 있어야 합니다.
127127

128128
```
129-
data: Message 1
129+
data: 메시지 1
130130
id: 1
131131
132-
data: Message 2
132+
data: 메시지 2
133133
id: 2
134134
135-
data: Message 3
136-
data: of two lines
135+
data: 메시지 3
136+
data: 두 번째 줄
137137
id: 3
138138
```
139139

140-
When a message with `id:` is received, the browser:
140+
`id:`가 붙은 메시지를 받으면 브라우저는 다음 두 가지 일을 합니다.
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+
- 프로퍼티 `eventSource.lastEventId`에 받은 값을 설정합니다.
143+
- 재연결 시 헤더 `Last-Event-ID`에 이 `id`를 실어 보내, 서버가 그다음 메시지부터 다시 보낼 수 있게 합니다.
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="`id:``data:` 뒤에 넣어주세요"
146+
주의하세요. 서버가 `id`를 메시지 `data` 아래에 붙이는 이유는 메시지를 다 받은 후에 `lastEventId`가 갱신되도록 보장하기 위해서입니다.
147147
```
148148
149-
## Connection status: readyState
149+
## readyState로 커넥션 상태 확인하기
150150
151-
The `EventSource` object has `readyState` property, that has one of three values:
151+
`EventSource` 객체의 프로퍼티 `readyState`는 세 값 중 하나를 갖습니다.
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; // 연결 중이거나 재연결 중
155+
EventSource.OPEN = 1; // 연결됨
156+
EventSource.CLOSED = 2; // 커넥션 닫힘
157157
```
158158

159-
When an object is created, or the connection is down, it's always `EventSource.CONNECTING` (equals `0`).
159+
객체가 막 만들어졌을 때나 커넥션이 끊어져 있을 때 값은 항상 `EventSource.CONNECTING`(`0`)입니다.
160160

161-
We can query this property to know the state of `EventSource`.
161+
이 프로퍼티를 조회하면 `EventSource`의 상태를 알 수 있습니다.
162162

163-
## Event types
163+
## 이벤트 타입
164164

165-
By default `EventSource` object generates three events:
165+
기본적으로 `EventSource` 객체는 세 가지 이벤트를 만들어냅니다.
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` -- 메시지가 도착함. 내용은 `event.data`로 접근
168+
- `open` -- 커넥션이 열림
169+
- `error` -- 커넥션을 맺지 못함. 서버가 HTTP 상태 코드 500을 반환한 경우 등
170170

171-
The server may specify another type of event with `event: ...` at the event start.
171+
서버는 이벤트 시작 부분에 `event: ...`를 붙여 다른 타입의 이벤트를 지정할 수 있습니다.
172172

173-
For example:
173+
예시를 살펴봅시다.
174174

175175
```
176176
event: join
177-
data: Bob
177+
data: 보라
178178
179-
data: Hello
179+
data: 안녕하세요.
180180
181181
event: leave
182-
data: Bob
182+
data: 보라
183183
```
184184

185-
To handle custom events, we must use `addEventListener`, not `onmessage`:
185+
이런 커스텀 이벤트를 처리하려면 `onmessage`가 아니라 `addEventListener`를 사용해야 합니다.
186186

187187
```js
188188
eventSource.addEventListener('join', event => {
189-
alert(`Joined ${event.data}`);
189+
alert(`${event.data}님이 입장했습니다.`);
190190
});
191191

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

196196
eventSource.addEventListener('leave', event => {
197-
alert(`Left ${event.data}`);
197+
alert(`${event.data}님이 퇴장했습니다.`);
198198
});
199199
```
200200

201-
## Full example
201+
## 전체 예시
202202

203-
Here's the server that sends messages with `1`, `2`, `3`, then `bye` and breaks the connection.
203+
아래 서버는 `1`, `2`, `3`을 차례로 보내고 마지막에 `bye`를 보낸 뒤 커넥션을 끊습니다.
204204

205-
Then the browser automatically reconnects.
205+
커넥션이 끊어지면 브라우저가 자동으로 재연결하는 것을 확인해 보세요.
206206

207207
[codetabs src="eventsource"]
208208

209-
## Summary
209+
## 요약
210210

211-
`EventSource` object automatically establishes a persistent connection and allows the server to send messages over it.
211+
`EventSource` 객체는 지속적인 커넥션을 자동으로 맺고, 서버가 이 커넥션을 통해 메시지를 보낼 수 있게 해줍니다.
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+
`EventSource`는 다음 기능을 제공합니다.
214+
- 자동 재연결. 재시도 간격은 `retry`로 조정 가능
215+
- 이벤트를 이어받기 위한 메시지 id. 마지막으로 받은 식별자는 재연결 시 `Last-Event-ID` 헤더에 실려 전송됨
216+
- 프로퍼티 `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+
이런 내장 기능 덕분에 `EventSource``WebSocket`의 훌륭한 대안이 됩니다. `WebSocket`은 더 저수준이라 이런 기능을 직접 구현해야 하기 때문입니다.
219219

220-
In many real-life applications, the power of `EventSource` is just enough.
220+
실제 애플리케이션 상당수엔 `EventSource`가 제공하는 능력만으로도 충분합니다.
221221

222-
Supported in all modern browsers (not IE).
222+
`EventSource`는 IE를 제외한 모든 모던 브라우저에서 지원합니다.
223223

224-
The syntax is:
224+
문법은 다음과 같습니다.
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+
두 번째 인수에 쓸 수 있는 옵션은 `{ withCredentials: true }` 하나뿐입니다. 이 옵션을 켜면 크로스 오리진 자격 증명을 보낼 수 있습니다.
231231

232-
Overall cross-origin security is same as for `fetch` and other network methods.
232+
전반적인 크로스 오리진 보안 정책은 `fetch` 등 다른 네트워크 메서드와 같습니다.
233233

234-
### Properties of an `EventSource` object
234+
### `EventSource` 객체의 프로퍼티
235235

236236
`readyState`
237-
: The current connection state: either `EventSource.CONNECTING (=0)`, `EventSource.OPEN (=1)` or `EventSource.CLOSED (=2)`.
237+
: 현재 커넥션 상태. `EventSource.CONNECTING (=0)`, `EventSource.OPEN (=1)`, `EventSource.CLOSED (=2)` 중 하나
238238

239239
`lastEventId`
240-
: The last received `id`. Upon reconnection the browser sends it in the header `Last-Event-ID`.
240+
: 마지막으로 받은 `id`. 재연결 시 브라우저는 이 값을 헤더 `Last-Event-ID`에 실어 보냄
241241

242-
### Methods
242+
### 메서드
243243

244244
`close()`
245-
: Closes the connection.
245+
: 커넥션을 닫음
246246

247-
### Events
247+
### 이벤트
248248

249249
`message`
250-
: Message received, the data is in `event.data`.
250+
: 메시지가 도착함. 데이터는 `event.data`에 저장됨
251251

252252
`open`
253-
: The connection is established.
253+
: 커넥션이 맺어짐
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+
: 에러가 발생함. 자동 재연결이 이어지는 커넥션 유실과 치명적인 에러 모두 해당됨. 재연결 시도 중인지는 `readyState`로 확인 가능
257257

258-
The server may set a custom event name in `event:`. Such events should be handled using `addEventListener`, not `on<event>`.
258+
서버는 `event:`에 커스텀 이벤트 이름을 지정할 수 있습니다. 이런 이벤트는 `on<event>`가 아니라 `addEventListener`로 처리해야 합니다.
259259

260-
### Server response format
260+
### 서버 응답 형식
261261

262-
The server sends messages, delimited by `\n\n`.
262+
서버는 메시지를 `\n\n`으로 구분해 보냅니다.
263263

264-
A message may have following fields:
264+
메시지엔 다음 필드가 들어갈 수 있습니다.
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:` -- 메시지 본문. 연속된 `data`는 부분 사이에 `\n`이 있는 하나의 메시지로 해석됨
267+
- `id:` -- `lastEventId`를 갱신함. 재연결 시 `Last-Event-ID`로 전송됨
268+
- `retry:` -- 재연결 지연 시간(밀리초)을 권장함. 자바스크립트에서 설정하는 방법은 없음
269+
- `event:` -- 이벤트 이름. `data:`보다 앞에 와야 함
270270

271-
A message may include one or more fields in any order, but `id:` usually goes the last.
271+
필드는 어떤 순서로든 하나 이상 넣을 수 있는데 관례상 `id:`를 마지막에 둡니다.

0 commit comments

Comments
 (0)