
웹 실시간 통신 파헤치기(1)에 이은 두번째글이다.
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.
출처: MDN
위의 설명에 따르면, 전통적으로 웹페이지는 새로운 데이터를 받기 위해 서버에 요청을 보낸다(클라이언트 → 서버). 하지만 SSE를 사용하면 서버에서 필요할 때마다 데이터를 웹 페이지로 푸시할 수 있다.
SSE의 특징을 알기 쉽도록 WebSocket과 비교해보겠다.
SSE
WebSocket

var source = new EventSource('updates.cgi');
1) 데이터만 있는 메시지
// 두 줄 이상의 연속된 줄은 하나의 데이터 블록으로 간주된다.
// 마지막 행을 제외한 줄은 \n(마지막 행은 \n\n)
data: This is the first message.
data: This is the second message, it
data: has two lines.
data: This is the third message.
2) 이벤트명이 설정된 메시지
예를 들어 클라이언트에서 이벤트 핸들러를 등록하면,
var source = new EventSource('updates.cgi');
source.addEventListener('add', addHandler, false);
source.addEventListener('remove', removeHandler, false);
서버에서는 아래와 같이 응답한다.
event: add
data: {"username": "bobby", "time": "02:33:48"}
event: remove
data: {"username": "bobby", "time": "02:33:48"}
event: add
data: {"username": "sean", "time": "02:34:36"}
여기서 data가 반드시 JSON일 필요는 없으며 첫번째 예시에서 보았듯 텍스트여도 가능하다.
3) id가 포함된 메시지
data: first event
id: 1
data: second event
id
data: third event
첫 번째 블록에는 이름이 각각 data와 id인 두 개의 필드가 있다.
여기서 data: first event라는 데이터로 이벤트가 발생한다.
id는 1로 설정되어있는데, id는 마지막으로 수신한 데이터의 id이다.
id를 설정하면 브라우저가 마지막 이벤트를 추적해 서버 연결이 끊어지면 Last-Event-ID 헤더가 요청으로 설정된다.
이 값을 이용하여 서버는 유실된 데이터를 재전송 할 수 있게 된다.
두 번째 블록의 data 필드에는 second event가, id필드에는 값이 없다.
여기서 data: second event라는 라는 데이터로 이벤트가 발생한다.
id 필드가 비어있는데, 이것은 Last-Event-ID를 빈 문자열로 재설정해(Last-Event-ID 헤더가 없음을 의미), 다시 연결을 시도하는 경우 전송된다.
만약 SSE연결이 시간 만료 등의 이유로 끊어졌을 때 알림이 발생하면 어떻게 될까?
그 시간 동안 발생한 알림은 클라이언트에 전달되지 못할 것이다.
이를 방지해 주는 것이 Last-Event-ID헤더이다. 이 헤더 값을 이용하여 서버는 유실된 데이터를 재전송 할 수 있게 된다.
공식문서
https://html.spec.whatwg.org/multipage/server-sent-events.html
왜 Last-Event-ID를 사용하는가
https://stackoverflow.com/a/58374643
velog
https://velog.io/@max9106/Spring-SSE-Server-Sent-Events%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%8B%A4%EC%8B%9C%EA%B0%84-%EC%95%8C%EB%A6%BC
GeekNews, Hacker news
https://news.hada.io/topic?id=5972
https://news.ycombinator.com/item?id=30312897