SSE(Server-Sent Events)

 

서버 전송 이벤트를 사용하면 업데이트가 자동으로 제공됩니다.

 

예: Facebook/Twitter 업데이트, 주가 업데이트, 뉴스 피드, 스포츠 결과

 

 

 

 

간단한 예제

 

<!DOCTYPE html>
<html>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("demo_sse.php");
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
  };
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

 

 

예시 설명

 

EventSource 객체는 서버에서 보낸 이벤트 알림을 받는 데 사용한다

 

업데이트가 수신될 때마다 onmessage 이벤트가 발생합니다.

 

onmessage 이벤트 발생 시 받은 데이터를 id="result"인 요소에 넣습니다.

 

 

위의 예가 작동하려면 데이터 업데이트(예: PHP 또는 ASP)를 보낼 수 있는 서버가 필요하다

 

서버측 이벤트 스트림 구문은 간단합니다. 

"Content-Type" 헤더를 "text/event-stream"으로 설정합니다. 

이제 이벤트 스트림 전송을 시작할 수 있습니다.

 

//PHP일때

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

 

"Content-Type" 헤더를 "text/event-stream"으로 설정합니다.

페이지를 캐시하지 않도록 지정

보낼 데이터 출력( 항상 "data: "로 시작)

출력 데이터를 웹 페이지로 다시 플러시

 

 

 

 

 

//ASP일때

<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>

 

'Web > HTML' 카테고리의 다른 글

HTML 웹 작업자 API  (0) 2023.01.04
HTML 웹 저장소 API  (0) 2023.01.04
HTML 드래그 앤 드롭 API  (0) 2023.01.04
HTML 위치 정보 API  (0) 2023.01.03
HTML 플러그인  (0) 2023.01.03

+ Recent posts