[js] SSE (Server-Sent-Event)

Edward Hyun·2022년 5월 31일
0

app&web-dev

목록 보기
116/178

SSE는 서버와 Jsavascript가 서로 통신함.
브라우저에서 직접 처리되므로 사용자는 메시지를 구독함.

JavaScript API
이벤트 스트림을 구독하려면 EventSource 객체를 만들고 스트림의 URL을 전달합니다.

if (!!window.EventSource) {
  var source = new EventSource('stream.php');
} else {
  // Result to xhr polling :(
}

참고 : EventSource 생성자에 전달 된 URL이 절대 URL 인 경우 해당 출처 (scheme, domain, port)가 호출 페이지의 출처와 일치해야합니다.그런 다음 메시지 이벤트에 대한 핸들러를 설정하십시오. 선택적으로 open 과 error 를 수신 대기 할 수 있습니다.

source.addEventListener('message', function(e) {
  console.log(e.data);
}, false);

source.addEventListener('open', function(e) {
  // Connection was opened.
}, false);

source.addEventListener('error', function(e) {
  if (e.readyState == EventSource.CLOSED) {
    // Connection was closed.
  }
}, false);

출처:
https://www.html5rocks.com/en/tutorials/eventsource/basics/
https://hamait.tistory.com/792
https://velog.io/@max9106/Spring-SSE-Server-Sent-Events를-이용한-실시간-알림
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
https://www.hahwul.com/cullinan/sse/

profile
앱&웹개발(flutter, vuejs, typescript, react), 인공지능(nlp, asr, rl), 백엔드(nodejs, flask, golang, grpc, webrtc, aws, msa, nft, spring cloud, nest.js), 함수형 프로그래밍(scala, erlang)을 공부하며 정리합니다.

0개의 댓글